根据用户选择,我想在按下按钮时打开一个或另一个活动。我还试图只设置一个Listener,并根据boolean来设置一个或另一个活动,但是我得到了#34;变量是从内部类中访问的,需要在final和' #34;错误。谢谢!
but1 = (Button) findViewById(R.id.start);
RadioButton selectionA = (RadioButton) findViewById(R.id.buttonSelectionA);
boolean VocabularySelected = selectionA.isChecked();
RadioButton selectionB = (RadioButton) findViewById(R.id.buttonSelectionB);
boolean MathSelected = selectionB.isChecked();
if (VocabularySelected) {
but1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent Vocabulary = new Intent(MainActivity.this, VocabularyActivity.class);
startActivity(Vocabulary);
}
});
}
if (MathSelected) {
but1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent Math = new Intent(MainActivity.this, MathActivity.class);
startActivity(Math);
}
});
}
答案 0 :(得分:0)
为什么不使用相同的点击监听器,在其中根据布尔值执行逻辑?
but1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (MathSelected) {
Intent Math = new Intent(MainActivity.this, MathActivity.class);
startActivity(Math);
} else if(VocabularySelected) {
Intent Vocabulary = new Intent(MainActivity.this, VocabularyActivity.class);
startActivity(Vocabulary);
}
}
});
答案 1 :(得分:0)
一个视图只能分配一个OnClickListener
,因此您需要检查一下侦听器中的路径。
为避免访问非最终变量的错误,您可以用另一种方式执行检查。也许是这样的:
but1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RadioButton selectionA = (RadioButton) findViewById(R.id.buttonSelectionA);
RadioButton selectionB = (RadioButton) findViewById(R.id.buttonSelectionB);
if (selectionA.isChecked()) {
Intent Vocabulary = new Intent(MainActivity.this, VocabularyActivity.class);
startActivity(Vocabulary);
else if (selectionB.isChecked()) {
Intent Math = new Intent(MainActivity.this, MathActivity.class);
startActivity(Math);
}
}
});
答案 2 :(得分:0)
有很多方法可以做到这一点,这是我的最爱之一,通过在听众中引用视图本身:
but1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (((RadioButton) findViewById(R.id.buttonSelectionA)).isChecked()) {
Intent Vocabulary = new Intent(MainActivity.this, VocabularyActivity.class);
startActivity(Vocabulary);
} else if (((RadioButton) findViewById(R.id.buttonSelectionB)).isChecked()) {
Intent Math = new Intent(MainActivity.this, MathActivity.class);
startActivity(Math);
}
}
});
它不是最易读的,但最短的。
你也可以将你的布尔变量声明为类的成员,并在一个监听器中使用它们,如下所示:
public class YourActivity extends AppCompatActivity{
...
private boolean mVocabularyChecked, mMathChecked;
...
private void yourMethod() {
but1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mVocabularyChecked) {
Intent Vocabulary = new Intent(MainActivity.this, VocabularyActivity.class);
startActivity(Vocabulary);
} else if (mMathChecked) {
Intent Math = new Intent(MainActivity.this, MathActivity.class);
startActivity(Math);
}
}
});
}