在 Android 中,創建自定義監聽器需要以下幾個步驟:
CustomClickListener
的接口:public interface CustomClickListener {
void onCustomClick(int position);
}
public class CustomView extends View {
private CustomClickListener customClickListener;
public void setCustomClickListener(CustomClickListener listener) {
this.customClickListener = listener;
}
public void removeCustomClickListener() {
this.customClickListener = null;
}
}
onCustomClick
方法:public class CustomView extends View {
// ...
@Override
public boolean performClick() {
super.performClick();
if (customClickListener != null) {
customClickListener.onCustomClick(/* 傳遞你需要的參數 */);
}
return true;
}
}
public class MainActivity extends AppCompatActivity implements CustomClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomView customView = findViewById(R.id.custom_view);
customView.setCustomClickListener(this);
}
@Override
public void onCustomClick(int position) {
// 處理自定義點擊事件
}
}
現在,當用戶點擊自定義 View 時,onCustomClick
方法將會被調用,你可以在這里處理相應的邏輯。