Hub*_*ert 45 android button listener
假设我在LinearLayout中有几个按钮,其中2个是:
mycards_button = ((Button)this.findViewById(R.id.Button_MyCards));
exit_button = ((Button)this.findViewById(R.id.Button_Exit));
Run Code Online (Sandbox Code Playgroud)
我注册setOnClickListener()了他们两个:
mycards_button.setOnClickListener(this);
exit_button.setOnClickListener(this);
Run Code Online (Sandbox Code Playgroud)
如何使SWITCH区分Onclick中的两个按钮?
public void onClick(View v) {
switch(?????){
case ???:
/** Start a new Activity MyCards.java */
Intent intent = new Intent(this, MyCards.class);
this.startActivity(intent);
break;
case ???:
/** AlerDialog when click on Exit */
MyAlertDialog();
break;
}
Run Code Online (Sandbox Code Playgroud)
Int*_*ons 118
使用:
public void onClick(View v) {
switch(v.getId()){
case R.id.Button_MyCards: /** Start a new Activity MyCards.java */
Intent intent = new Intent(this, MyCards.class);
this.startActivity(intent);
break;
case R.id.Button_Exit: /** AlerDialog when click on Exit */
MyAlertDialog();
break;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这不适用于Android库项目(由于http://tools.android.com/tips/non-constant-fields),您需要使用以下内容:
int id = view.getId();
if (id == R.id.Button_MyCards) {
action1();
} else if (id == R.id.Button_Exit) {
action2();
}
Run Code Online (Sandbox Code Playgroud)
另一个选项是在setOnClickListener()中添加一个新的OnClickListener作为参数并覆盖onClick() - 方法:
mycards_button = ((Button)this.findViewById(R.id.Button_MyCards));
exit_button = ((Button)this.findViewById(R.id.Button_Exit));
// Add onClickListener to mycards_button
mycards_button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// Start new activity
Intent intent = new Intent(this, MyCards.class);
this.startActivity(intent);
}
});
// Add onClickListener to exit_button
exit_button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// Display alertDialog
MyAlertDialog();
}
});
Run Code Online (Sandbox Code Playgroud)
小智 5
public class MainActivity extends Activity
implements View.OnClickListener {
private Button btnForward, btnBackword, btnPause, btnPlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControl();
}
private void initControl() {
btnForward = (Button) findViewById(R.id.btnForward);
btnBackword = (Button) findViewById(R.id.btnBackword);
btnPause = (Button) findViewById(R.id.btnPause);
btnPlay = (Button) findViewById(R.id.btnPlay);
btnForward.setOnClickListener(this);
btnBackword.setOnClickListener(this);
btnPause.setOnClickListener(this);
btnPlay.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnForward:
break;
case R.id.btnBackword:
break;
case R.id.btnPause:
break;
case R.id.btnPlay:
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)