gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:34:46 25 4
gpt4 key购买 nike

//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 中的字符串时,它都会出现错误

这是我遇到困难时使用的代码,我直接输入 ids 而没有输入 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);
}

最佳答案

您需要为每个要检索的 View 设置一个 ID。例如:

<RelativeLayout
... >
<TextView
android:id="@+id/text_1"
... />

<TextView
android:id="@+id/text_2"
... />
//...

然后您可以使用 id 检索 Java 代码中的 View

TextView tv1 = (TextView) findViewById(R.id.text_1);
TextView tv2 = (TextView) findViewById(R.id.text_2);

除了 int 之外,您不能使用其他任何东西来通过 id 检索 View 。如果您想将 id 传递给方法,只需执行以下操作:

methodUsingId(R.id.text_1);


public void methodUsingId(@IdRes int viewId){
//...
}

请注意,仅当您想对其执行某些操作时,才需要通过 id 查找 View 。如果您已经拥有它,则无需这样做。

关于java - 如何在方法中插入 id 作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49028108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com