首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 從 XML 佈局引用 ImageView:LayoutInflater.findViewById 正確用法

     編輯:程式設計綜合問答

在 SurfaceView 基礎上動態添加控制層佈局 control.xml,其中包含 ImageView。需在 Java 代碼中獲取該 ImageView 引用。關鍵是對 LayoutInflater 返回的 View 呼叫 findViewById,而非 Activity。

代碼現場


// onCreate 中
setContentView(R.layout.main); // 主佈局含 SurfaceView
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.control, null); // 加載控制層
this.addContentView(viewControl, new LayoutParams(MATCH_PARENT, MATCH_PARENT));



    

正確引用方式


// ❌ 錯誤:在 Activity 上找,找不到(ImageView 不在 main.xml)
ImageView img = findViewById(R.id.img); 

// ✅ 正確:在 inflated View 上找
ImageView img = viewControl.findViewById(R.id.img);
// 或
ImageView img = (ImageView) controlInflater.findViewById(R.id.img); // 同理

原理圖解


Activity.findViewById() → 搜尋 setContentView() 設置的視圖樹 (main.xml)
viewControl.findViewById() → 搜尋 viewControl 這棵子樹 (control.xml)

關於 SurfaceView + 覆蓋層的架構建議

  • SurfaceView 打洞特性:SurfaceView 在視圖層級會「打洞」,覆蓋在上層的普通 View 可能被遮擋或觸摸事件穿透
  • 推薦做法:
    1. 自定義 CameraPreview extends SurfaceView,在 onDraw(Canvas) 中直接 canvas.drawBitmap() 繪製控制圖標
    2. 或用 TextureView(API 14+)替代 SurfaceView,可像普通 View 一樣動畫、透明度、佈局嵌套
  • 若必須用 addContentView 疊加層,確保 viewControl 背景透明、不攔截觸摸(或按需攔截)

總結

動態加載佈局後,在返回的 View 對象上調用 findViewById 獲取子控件。SurfaceView 疊加普通 View 存在打洞與觸摸穿透問題,建議改用 TextureView 或在 SurfaceView.onDraw 中直接繪製 UI 元素。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved