我创建了一个扩展 Button 的新类:
public class MyButton extends Button {
public static final int STATUS_OFF = 0;
public static final int STATUS_PLAY1 = 1;
public static final int STATUS_PLAY2 = 2;
public static final int STATUS_PLAY3 = 3;
public int status;
private Context ctx;
public MyButton(Context context) {
super(context);
ctx = context;
status = STATUS_OFF;
super.setBackgroundResource(R.drawable.sound_button_off);
}
private void click() {
switch (status) {
case STATUS_OFF:
status = STATUS_PLAY1;
break;
case STATUS_PLAY1:
status = STATUS_PLAY2;
break;
case STATUS_PLAY2:
status = STATUS_OFF;
break;
case STATUS_PLAY3:
break;
}
// OTHER THINGS TO DO
}
}
在我的主要活动中:
public class MyActivity extends Activity {
private static final int HORIZ = 16;
private MyButton[] b = new MyButton[HORIZ];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rhythm);
createButtons();
}
private void createButtons() {
LinearLayout layout = (LinearLayout)findViewById(R.id.layout_main_linear);
for (int w=0; w<HORIZ; w++) {
b[w] = new MyButton(MyActivity.this);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layout.addView(b[w], p);
b[w].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// HELP ME HERE
// WHEN CLICKING THIS BUTTON, IT AUTOMATICALLY SHOULD RUN the private method click();
// IT IS PRIVATE AND SHOULD NOT BE RUN FROM HERE, BUT AUTOMATICALLY EACH TIME THE BUTTON IS CLICKED.
}
});
}
}
}
当我从主类中 setOnClickListener() 时,如何自动调用 click() 方法?换句话说,这个按钮应该像任何其他按钮一样工作,但在单击时执行更多操作。