这是您可以在下面执行的一种方法。在此示例中,您将在屏幕上放置 3 个按钮。这些是我在 XML 文件中定义和布局的按钮。单击 3 个不同按钮中的任何一个,它会将您带到相应的活动。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Here is code to go grab and layout the Buttons, they're named b1, b2, etc. and identified as such.
Button b1 =(Button)findViewById(R.id.b1);
Button b2 =(Button)findViewById(R.id.b2);
Button b3 =(Button)findViewById(R.id.b3);
// Setup the listeners for the buttons, and the button handler
b1.setOnClickListener(buttonhandler);
b2.setOnClickListener(buttonhandler);
b3.setOnClickListener(buttonhandler);
}
View.OnClickListener buttonhandler=new View.OnClickListener() {
// Now I need to determine which button was clicked, and which intent or activity to launch.
public void onClick(View v) {
switch(v.getId()) {
// Now, which button did they press, and take me to that class/activity
case R.id.b1: //<<---- notice end line with colon, not a semicolon
Intent myIntent1 = new Intent(yourAppNamehere.this, theNextActivtyIwant.class);
YourAppNameHere.this.startActivity(myIntent1);
break;
case R.id.b2: //<<---- notice end line with colon, not a semicolon
Intent myIntent2 = new Intent(yourMainAppNamehere.this, AnotherActivtyIwant.class);
YourAppNameHere.this.startActivity(myIntent2);
break;
case R.id.b3:
Intent myIntent3 = new Intent(yourMainAppNamehere.this, a3rdActivtyIwant.class);
YourAppNameHere.this.startActivity(myIntent3);
break;
}
}
};
}
基本上我们正在做几件事来设置它。识别按钮并将它们从 XML 布局中拉入。看看每个人是如何分配一个 id 名称的。r.id.b1 例如是我的第一个按钮。
然后我们设置了一个处理程序,它监听我的按钮的点击。接下来,需要知道按下了哪个按钮。开关/案例就像一个“如果那么”。如果他们按下按钮 b1,代码会将我们带到我们分配给该按钮单击的内容。按下 b1(按钮 1),然后我们转到我们分配给它的“意图”或活动。
希望这会有所帮助,如果有任何用处,请不要忘记投票。我自己才刚刚开始研究这些东西。
谢谢,