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

Android SurfaceView 與 Activity 通信:回調接口模式實現跨組件數據傳遞

     編輯:程式設計綜合問答

場景

MainActivity 包含 SurfaceView 與 TextView。SurfaceView 觸摸事件計數 step++,需實時更新 TextView 顯示。

解耦方案:定義回調接口

1. 接口定義

public interface OnStepChangeListener {
    void onStepChanged(int step);
}

2. SurfaceView 持有接口引用


public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
    private OnStepChangeListener listener;
    private int step = 0;

    public MySurfaceView(Context context) {
        super(context);
        getHolder().addCallback(this);
    }

    public void setOnStepChangeListener(OnStepChangeListener listener) {
        this.listener = listener;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            step++;
            if (listener != null) {
                listener.onStepChanged(step); // 回調通知
            }
        }
        return true;
    }
    // ... surfaceCreated/Changed/Destroyed
}

3. Activity 實現接口並綁定


public class MainActivity extends Activity implements OnStepChangeListener {
    private MySurfaceView surfaceView;
    private TextView tvStep;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        surfaceView = findViewById(R.id.surfaceView);
        tvStep = findViewById(R.id.tvStep);
        surfaceView.setOnStepChangeListener(this); // 關鍵:注冊回調
    }

    @Override
    public void onStepChanged(int step) {
        // 確保 UI 線程更新
        runOnUiThread(() -> tvStep.setText("Step: " + step));
    }
}

關鍵點

  • 接口解耦:SurfaceView 不依賴具體 Activity,可復用於 Fragment/Dialog 等宿主。
  • 線程安全:觸摸事件在 UI 線程,但若在繪制線程修改 step,必須用 runOnUiThread 或 Handler 更新 View。
  • 生命週期:onDestroy 時置空 listener 防止內存洩漏。

擴展:EventBus / LiveData / Flow

大型項目可採用 EventBus (Greenrobot) 或 Jetpack LiveData/Flow 實現組件間響應式通信,進一步降低耦合。

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