//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();
        }

    }
}


这是代码,如果我尝试将参数设为字符串,则它给我一个错误,表明在findviewbyid中使用它必须是一个int
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);
}

最佳答案

您需要在要检索的每个视图上设置一个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查找视图。如果已经有了,则不需要这样做。

10-04 18:16