所以,我正在尝试编写代码来显示单选按钮点击注册。理想情况下,当一个单选按钮被选中时,TextView 的内容将会改变。首先,我有一个“北”单选按钮。选中 North 时,TextView 的内容将变为“North”。我知道涉及 Action 监听器,但我不熟悉 Java。这肯定会弹出我的 Java 樱桃。话虽如此,我编写的代码不起作用。谁能告诉我我是否在正确的轨道上,或者提供一些建议?请注意,这不是类作业。这是一个非常开放的类项目,我正在与另一个人合作。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View v){
TextView text = (TextView)findViewById(R.id.text);
RadioButton N = (RadioButton) findViewById(R.id.north);
//evaluates 'checked' value of radio button
boolean checked = ((RadioButton) v).isChecked();
if(N.isChecked () ){
text.setText("N");
}
}
最佳答案
要正确使用RadioButton
,您最好将一堆RadioButton
分组到一个名为RadioGroup
的集合中。
<RadioGroup
android:id="@+id/rg1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioButton
android:id="@+id/rg1_rb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="North" />
<RadioButton
android:id="@+id/rg1_rb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="South" />
<RadioButton
android:id="@+id/rg1_rb3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Whatever" />
</RadioGroup>
关键部分是您必须为每个 RadioButton
设置唯一的 android:id
,否则它们将无法工作!
接下来,从您的 XML 中找到 RadioButton
。
RadioButton rb1, rb2, rb3;
rb1 = (RadioButton) findViewById(R.id.rg1_rb1);
rb2 = (RadioButton) findViewById(R.id.rg1_rb2);
rb3 = (RadioButton) findViewById(R.id.rg1_rb3);
最后,准备一个RadioButton.OnClickListener
类实例并将其附加到RadioButton
。
View.OnClickListener optionOnClickListener
= new View.OnClickListener() {
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.textview);
String str = null;
// you can simply copy the string of clicked button.
str = ((RadioButton)v).getText().toString();
tv.setText(str);
// to go further with check state you can manually check each radiobutton and find which one is checked.
if(rb1.isChecked()) {
// do something
}
if(rb2.isChecked()) {
// do something
}
if(rb3.isChecked()) {
// do something
}
}
};
rb1.setOnClickListener(optionOnClickListener);
rb2.setOnClickListener(optionOnClickListener);
rb3.setOnClickListener(optionOnClickListener);
// check rb1 by default, if you want.
rb1.setChecked(true);
添加:
很抱歉,我无法理解我的答案的编辑版本,因为在 View.OnClickLister.OnClick() 中调用 setOnClickListener() 对我来说有点奇怪。
所以我回滚到原来的答案。
关于java - Android:使用单选按钮更改 TextView 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42476083/