我在MainActivity上有2个按钮。我想要第一个按钮将我发送到TestPage1.class(它已经做了)。我想要第二个按钮将我发送到TestPage2.class。每当我点击第二个按钮时,它会直接发送给TestPage1而不是TestPage2。我怎样才能做到这一点?
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
public class MainActivity extends ActionBarActivity implements OnClickListener {
Button button1, button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = ((Button) findViewById(R.id.button1));
button1.setOnClickListener(this);
button2 = ((Button) findViewById(R.id.button2));
button2.setOnClickListener(this);
}
@Override public void onClick(View v) {
startActivity(new Intent(MainActivity.this, TestPage1.class));
}
public void onClick2(View v){
startActivity(new Intent(MainActivity.this, TestPage2.class));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:3)
在onClick(View v)
switch(v.getId()) {
case R.id.button1:
// do stuff;
break;
case R.id.button2:
// do stuff;
break;
...
答案 1 :(得分:1)
使用v.getId()
检查onClick方法中单击的Button:
@Override
public void onClick(View v) {
if(v.getId()==R.id.button1)
startActivity(new Intent(MainActivity.this, TestPage1.class));
}
或使用switch-case
用同一个侦听器处理多个Button点击:
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
// ... your code here...
break;
case R.id.button2:
// ... your code here...
break;
default:
//...
}
}
答案 2 :(得分:0)
// declare buttons b1,b2
// remove "implements onclick listener" and use this
enter code here
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent inten = new Intent(this,
TestPage1.class);
startActivity(inten);
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent inten = new Intent(this,
TestPage2.class);
startActivity(inten);
finish();
}
});