如何在方法中插入id作为参数?

问题描述 投票:0回答:1
//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);
}
java android
1个回答
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查找视图。如果你已经拥有它,你不需要这样做。

热门问题
推荐问题
最新问题