[英]Android: Same activity for different buttons, but different actions
I was wondering if there is any way to call the same activity for different buttons, but do different things for each one.. 我想知道是否有任何方法可以为不同的按钮调用同一活动,但为每个按钮执行不同的操作。
More specific.. I have one activity with about 10 buttons on it and if I do it traditionally, every time I press a button, I have to create an activity for each one and as a result, I will have more than 15 java files.. 更具体地说..我有一个活动,上面有大约10个按钮,如果按传统方式做,每次按一个按钮,我都必须为每个活动创建一个活动,结果,我将有15个以上的Java文件..
So, I was wondering if there is any way, all the buttons, show to the same activity (which is easy, I will "intent" to show the same activity), but on that activity, depending on the button I press, do different actions.. 因此,我想知道所有按钮是否都可以显示相同的活动(这很容易,我将“意图”显示相同的活动),但是在该活动上,取决于我按下的按钮,不同的动作
For example, all the buttons show on Buttons.java, but inside exist a TextView and every time show another text, depending on the buttons I press -> Text1 (for Button1), Text2 (for Button2), Text3 (for Button3)... 例如,所有按钮都显示在Buttons.java上,但是内部存在一个TextView,每次显示另一个文本,具体取决于我按下的按钮-> Text1(对于Button1),Text2(对于Button2),Text3(对于Button3)。 ..
Do you have any ideas?? 你有什么想法?? Thank you!!
谢谢!!
You can pass some information to activity when you want to start it... for example: 您可以在想要启动活动时将一些信息传递给活动...例如:
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), ExampleActivity.class);
//There is no limit for number of Extras you want to pass to activity
intent.putExtra("buttonNumber", 1);
startActivity(intent);
}
});
ExampleActivity.java ExampleActivity.java
public class ExampleActivity extends Activity {
int pressedButtonNumber;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_poll);
pressedButtonNumber = getIntent().getExtras().getInt("buttonNumber");
switch(pressedButtonNumber){
case 1:
//Do Something for clicking button 1 scenario
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.