在 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)
CameraPreview extends SurfaceView,在 onDraw(Canvas) 中直接 canvas.drawBitmap() 繪製控制圖標TextureView(API 14+)替代 SurfaceView,可像普通 View 一樣動畫、透明度、佈局嵌套addContentView 疊加層,確保 viewControl 背景透明、不攔截觸摸(或按需攔截)動態加載佈局後,在返回的 View 對象上調用 findViewById 獲取子控件。SurfaceView 疊加普通 View 存在打洞與觸摸穿透問題,建議改用 TextureView 或在 SurfaceView.onDraw 中直接繪製 UI 元素。