我有几个按钮,我希望每个按钮都转到另一个xml页面。我有一个按钮的代码到一个页面正常工作。但我无法通过代码解决这个问题的解决方案。
@Override
protected void onCreate(Bundle savedInstanceStae){
super.onCreate(savedInstancesState);
setContentView(R.layout.activity_index);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(v.getContext(), voorbeeld.class);
startActivityForResult(intent, 0);
}
});
}
//This is only for one button, has somebody a solution to work with several buttons
答案 0 :(得分:3)
使用onclicklistener实现您的活动,并编写类似下面的代码
public class MainActiv1ity extends Activity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
Button button3 = (Button)findViewById(R.id.button3);
Button button4 = (Button)findViewById(R.id.button4);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
//do your logic
break;
case R.id.button2:
//do your logic
break;
case R.id.button3:
//do your logic
break;
case R.id.button4:
//do your logic
break;
default:
break;
}
}
}
答案 1 :(得分:1)
在每个按钮的XML中,添加一个新的android:onClick="methodName"
,每个按钮使用不同的methodName。
然后在您的活动类中,添加具有该名称的方法,该方法将视图作为参数并为每个创建新的意图:
public void methodName2(View view) {
Intent intent = new Intent(v.getContext(), activityForButton1.class);
startActivity(intent);
}
public void methodName2(View view) {
Intent intent = new Intent(v.getContext(), activityForButton2.class);
startActivity(intent);
}
public void methodName2(View view) {
Intent intent = new Intent(v.getContext(), activityForButton3.class);
startActivity(intent);
}