我在一个类中有两个按钮,这些按钮会将您发送到同一类,但根据按下的按钮,它将显示不同的文本/图像/按钮。
现在,当按下按钮时,它会将您带到下一个类并添加一些 intets,如下所示:
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bundle bundle1 = new Bundle();
bundle1.putInt("top", R.drawable.1);
bundle1.putInt("mid", R.drawable.2);
bundle1.putInt("bot", R.drawable.3);
Intent intet1 = new Intent(curclass.this, nextclass.class);
intent1.putExtras(bundle1);
startActivity(intent1);
在下一个类中,我为每个按钮都有一个 bundle ,但我相信我需要在它们上设置一个 if/else 以确保它只使用其中一个 bundle ,因为它现在无法正常工作。
那么我该如何做“如果”呢? 我试过了,但我不知道“如果”后面应该放什么。 类似的东西
"if (button1 = pressed)
(do this)
else if (button2 = pressed)
(do this)"
提前致谢!
抱歉,如果我像白痴一样解释,可能是因为我是其中之一,而且我刚刚开始编程。
编辑:问题是我在第二个 Activity 中有两个包,如下所示:
Bundle asd = getIntent().getExtras();
int asdasd = asd.getInt("top");
im1 = (ImageView) findViewById(R.id.imagetop);
im1.setImageResource(newimage);
bu1 = (Button) findViewById(R.id.buttontop);
bu1.setText("blahblah");
我在其下有中间和机器人,然后我有第二个 bundle ,它告诉按钮2的整数要显示什么图像/文本,问题是即使我按下按钮1,它也会加载第二个 bundle 的东西,这我怀疑这是由于 bundle 与任何告诉它们要做什么的东西并排在一起造成的。
我希望这能解决问题:)
最佳答案
bundle 的 get... 方法的好处是您可以定义默认值。
把它放在任何你想要的地方,也许你有一个常量类,或者你最好把它填充到哪里。由于它是静态的,因此您可以在任何地方访问它。 创建“全局变量”来唯一标识您的按钮。
public static final int no_button = -1;
public static final int button_1 = 1;
public static final int button_2 = 2; //you are not forced to use -1, 1, 2, just use different numbers
始终在您的第一个 Activity 中,按下按钮后
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bundle bundle1 = new Bundle();
bundle1.putInt("button id", button_1);
bundle1.putInt("top", R.drawable.1);
bundle1.putInt("mid", R.drawable.2);
bundle1.putInt("bot", R.drawable.3);
Intent intet1 = new Intent(curclass.this, nextclass.class);
intent1.putExtras(bundle1);
startActivity(intent1);
或
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bundle bundle2 = new Bundle();
bundle2.putInt("button id", button_2);
bundle2.putInt("top", R.drawable.1);
bundle2.putInt("mid", R.drawable.2);
bundle2.putInt("bot", R.drawable.3);
Intent intet2 = new Intent(curclass.this, nextclass.class);
intent2.putExtras(bundle1);
startActivity(intent1);
然后在第二个 Activity 中
Bundle asd = getIntent().getExtras();
switch(asd.getInt("button id", -1)){
case button_1:
[put here the code you want to execute if button1 was pressed]
case button_2:
[put here the code you want to execute if button2 was pressed]
case no_button:
[put here the code you want to execute if something else happened]
}
关于java - 根据按下的按钮加载包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8233838/