我在一个活动中提出了一些问题,每个答案都有一个要点(0到3)。例如,如果用户选择第一个,他得到0分,如果他选择了第一个,他将获得1分等(第三个为2分,第四个为3分)。
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.first_radiobutton) {
totalPoint = totalPoint + 0;
} else if (checkedId == R.id.secound_radiobutton) {
totalPoint = totalPoint + 1;
}else if (checkedId == R.id.third_radiobutton) {
totalPoint = totalPoint + 2;
}else if (checkedId == R.id.forth_radiobutton) {
totalPoint = totalPoint + 3;
}
}
});
我将totalPoint
作为全局变量并将其初始化为public static int totalPoint = 0;
。问题是,如果用户改变了主意并为当前问题选择了另一个答案,totalPoint
变量会将该点添加到自身。例如,假设如果用户点击第三个radioButton
,则totalPoint
变量将为2,因此如果用户改变了主意并选择了第四个radioButton
,则{{1必须是3,但它将是5(2 + 3)。我怎么能避免这个?
答案 0 :(得分:0)
在类
中声明一个int数组 int arrValues[]={0,0,0,0}; ///size can be differ as per question length you can create dynamic too as per your requirement
并维持问题的反击或立场
int iPosition=0;
///在上一个和下一个
然后在setOnCheckedChangeListener中添加以下代码
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.first_radiobutton) {
arrValues[iPosition] = 0;
} else if (checkedId == R.id.secound_radiobutton) {
arrValues[iPosition] = 1;
}else if (checkedId == R.id.third_radiobutton) {
arrValues[iPosition]= 2;
}else if (checkedId == R.id.forth_radiobutton) {
arrValues[iPosition] = 3;
}
}
});
并且最后一步从数组中添加所有值
答案 1 :(得分:0)
1。使用数组answers[]
存储特定points
的答案question
。
2。在onCheckedChanged()
中,选中RadioButton
,并使用{{1}的值将已分配的points
存储在特定的question
下}。
3。按currentQuestion
total
adding
数组values
计算answers
点数。
以下是工作代码:
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
int totalPoint = 0;
int answers[] = new int[10]; // Required for 10 questions (0 to 9)
int currentQuestion = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = (RadioGroup) findViewById(R.id.radio_group);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// Store points of specific question using position currentQuestion
if (checkedId == R.id.first_radiobutton) {
answers[currentQuestion] = 0;
} else if (checkedId == R.id.second_radiobutton) {
answers[currentQuestion] = 1;
}else if (checkedId == R.id.third_radiobutton) {
answers[currentQuestion] = 2;
}else if (checkedId == R.id.forth_radiobutton) {
answers[currentQuestion] = 3;
}
// Total
totalPoint = getTotalPoint();
}
});
}
public int getTotalPoint() {
int sum = 0;
for (int i = 0; i < answers.length; i++)
sum += answers[i];
return sum;
}
}