Android Studio中设计时,在前端设计了3个RadioButton和1个TextView,想在后台中控制,根据RadioButton的选择不同,TextView中显示不同内容。
但是不管RadioButton怎么西选,TextView都是空白
public class standardpage extends Activity {
@Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.standard);
RadioButton radioButton1=(RadioButton)findViewById(R.id.rbutton1);
RadioButton radioButton2=(RadioButton)findViewById(R.id.rbutton2);
RadioButton radioButton3=(RadioButton)findViewById(R.id.rbutton3);
TextView text1=(TextView)findViewById(R.id.textstandard);
if (radioButton1.isSelected())
{
text1.setText("123");
}
if (radioButton2.isSelected())
{
text1.setText("");
}
if (radioButton3.isSelected())
{
text1.setText("");
}
}
}
你这是初始化代码吧
初始化的时候 只执行一次
后面的按钮选中切换不会执行这部分代码的
还有初始化的时候 是不是三个按钮 都没有选中,所以三个if都没有执行
你可以试下将监听改一下
if(radioButton1.isChecked()==true)
{
text1.setText("123");
}
if(radioButton2.isChecked()==true)
{
text1.setText("");
}
if(radioButton3.isChecked()==true)
{
text1.setText("");
}
https://www.cnblogs.com/xfweb/p/10559922.html
写在onclick里面,比如:
radioButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (...)
...
}
});
可以参考下面代码
package com.example.customview2.ui.activity;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.example.customview2.R;
public class TestActivity extends AppCompatActivity {
private TextView mTvShow;
private RadioGroup mRg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
init();
}
private void init() {
mTvShow = findViewById(R.id.tv);
mRg = findViewById(R.id.radio_group);
mRg.setOnCheckedChangeListener(listenner);
}
private RadioGroup.OnCheckedChangeListener listenner = new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb1:
mTvShow.setText("123");
break;
case R.id.rb2:
mTvShow.setText("ABC");
break;
case R.id.rb3:
mTvShow.setText("789");
break;
}
}
};
}
在预览编写的布局时,textView不显示文字。只显示输入的字母。
折腾了老半天才发现自己打开的是Android studio32位版的,用64位的打开即可。
路径是在Android Studio安装目录的bin目录中。
代码里只写了进入界面的时候展示的判断,点击选择的时候你还要加上每个button的选中监听事件,就像普通按钮的点击事件一样
首先RadioButton是单选按钮,所以得用一个组给它组起来也就是RadioGroup,那这三个RadioButton放到RadioGroup里面去,然后再给RadioGroup设置setOnCheckedChangeListener这个监听事件,
rgAll.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb1:
text1.setText();
break;
case R.id.rb2://
text1.setText();
break;
}
}
});
就OK了
RadioButton的关键属性是checked,而非selected
加上点击事件就行了 只是初始化没有事件。要不然就再xml文件中 给radio button 子项目设置checked = true