我正在安卓java应用程序中构建一个用于检查答案的模块,但它不起作用。在调试过程中,它显示变量包含一个完全出乎意料的值。能请谁解释一下可能是什么问题吗?这是模块:
private void QuizOperations() {
Toast.makeText(QuizActivity.this,"quizOperation", Toast.LENGTH_SHORT).show();
answered = true; // when the question is already answered Set bool to true
RadioButton rbSelected = findViewById(rbGroup.getCheckedRadioButtonId());
int indexofchild =rbGroup.indexOfChild(rbSelected) +1;
int answerNr = indexofchild +1;
checkSolution(answerNr,rbSelected);// method checks if the answer that is selected by the user corresponds to the answer in the database
}
预定的方式是rbselected获取用户按下的RadioButton的索引,然后answerNr将此按钮的索引作为int。然后它传递给checksolution((函数,该函数检查answerNr是否对应于数据库中的正确答案。但是,在调试时,无论我按下哪个按钮,answerNr都会保持值5。
调试屏幕截图
如果需要任何额外的代码,请告诉我。非常感谢
这里有一个关于如何检测视图被按下的非常简单的例子,set/get-id from标记。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:background="#333333">
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/radioButton1"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/radioButton2"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/radioButton3"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
private String[] answers = {
"January",
"February",
"March",
};
private RadioButton rb1, rb2, rb3;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rb1 = findViewById(R.id.radioButton1);
rb2 = findViewById(R.id.radioButton2);
rb3 = findViewById(R.id.radioButton3);
rb1.setTag("0");
rb2.setTag("1");
rb3.setTag("2");
rb1.setOnClickListener(this);
rb2.setOnClickListener(this);
rb3.setOnClickListener(this);
}
@Override
public void onClick(View view)
{
final int index = Integer.parseInt((String)view.getTag());
switch(view.getId()) {
case R.id.radioButton1:
rb2.setChecked(false);
rb3.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton2:
rb1.setChecked(false);
rb3.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton3:
rb1.setChecked(false);
rb2.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
}
}
}