//submit procedure that takes the id of right radio group and the right radio button as input to check the right answer
private void submit(int right_radiobutton, int Radiogroup, int submission, int right_text) {
// The selected Radio Group
RadioGroup radioGroup = findViewById(Radiogroup);
//Get the user's name
EditText username = findViewById(R.id.name);
String name = username.getText().toString();
//Text that displays right or wrong
TextView right = findViewById(right_text);
//The right answer of the question
RadioButton right_answer = findViewById(right_radiobutton);
Boolean isRight = right_answer.isChecked();
// if statement which know whether the answer is right or wrong
if (isRight) {
right.setVisibility(View.VISIBLE);
Context context = getApplicationContext();
CharSequence text = getString(R.string.Right_Answer) + name;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
result++;
} else {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Context context = getApplicationContext();
CharSequence text = getString(R.string.question_answer);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else {
right.setText(getString(R.string.wrong));
right.setVisibility(View.VISIBLE);
//question 1 submit button
Button submit1 = findViewById(submission);
submit1.setVisibility(View.GONE);
radioGroup.setVisibility(View.GONE);
Context context = getApplicationContext();
CharSequence text = getString(R.string.wrong_answer);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}
这是代码如果我试图将参数作为字符串说它必须是一个int来在findviewbyid中使用它,它会给我一个错误 一个id数据类型是字符串,但只要我尝试在findviewbyid中使用它作为字符串,它就会给我一个错误
这是我以前遇到的代码,我直接输入了ID而没有输入 R.id.idname
public void submit1 (View view){
submit(right_answer,firstRadioGroup,R.id.submit1,right_text1);
}
这里是我得到正确答案之后我正在使用提交的代码,谢谢
public void submit1 (View view){
submit(R.id.right_answer,R.id.firstRadioGroup,R.id.submit1,R.id.right_text1);
}
答案 0 :(得分:1)
您需要在要检索的每个View上设置ID。 例如:
<RelativeLayout
... >
<TextView
android:id="@+id/text_1"
... />
<TextView
android:id="@+id/text_2"
... />
//...
然后,您可以使用id
检索Java代码中的视图TextView tv1 = (TextView) findViewById(R.id.text_1);
TextView tv2 = (TextView) findViewById(R.id.text_2);
您无法使用int
以外的任何其他内容来按ID检索视图。
如果您想将id传递给方法,请执行以下操作:
methodUsingId(R.id.text_1);
public void methodUsingId(@IdRes int viewId){
//...
}
请注意,只有在想要对其执行某些操作时,才需要按ID查找视图。如果你已经拥有它,你不需要这样做。