讲解python常用框架 radiobutton控件( 二 )


例子代码如下:
Button btnchange = (Button) findViewById(R.id.btnpost);
RadioGroup radgroup = (RadioGroup) findViewById(R.id.radioGroup);
//为radioGroup设置一个监听器:setOnCheckedChanged()
btnchange.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 0; i < radgroup.getChildCount(); i++) {
RadioButton rd = (RadioButton) radgroup.getChildAt(i);
if (rd.isChecked()) {
Toast.makeText(getApplicationContext(), “点击提交按钮,获取你选择的是:” + rd.getText(), Toast.LENGTH_LONG).show();
break;
}
}
}
});
运行效果图:
代码解析: 这里我们为提交按钮设置了一个setOnClickListener事件监听器,每次点击的话遍历一次RadioGroup判断哪个按钮被选中我们可以通过下述方法获得RadioButton的相关信息!
getChildCount( )获得按钮组中的单选按钮的数目;getChinldAt(i):根据索引值获取我们的单选按钮isChecked( ):判断按钮是否选中2)CheckBox(复选框)
如题复选框 , 即可以同时选中多个选项 , 至于获得选中的值 , 同样有两种方式: 1.为每个CheckBox添加事件:setOnCheckedChangeListener 2.弄一个按钮 , 在点击后 , 对每个checkbox进行判断:isChecked();
运行效果图:
实现代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener,CompoundButton.OnCheckedChangeListener{
private CheckBox cb_one;
private CheckBox cb_two;
private CheckBox cb_three;
private Button btn_send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cb_one = (CheckBox) findViewById(R.id.cb_one);
cb_two = (CheckBox) findViewById(R.id.cb_two);
cb_three = (CheckBox) findViewById(R.id.cb_three);
btn_send = (Button) findViewById(R.id.btn_send);
cb_one.setOnCheckedChangeListener(this);
cb_two.setOnCheckedChangeListener(this);
cb_three.setOnCheckedChangeListener(this);
btn_send.setOnClickListener(this);
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton.isChecked()) Toast.makeText(this,compoundButton.getText().toString(),Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View view) {
String choose = “”;
if(cb_one.isChecked())choose += cb_one.getText().toString() + “”;
if(cb_two.isChecked())choose += cb_two.getText().toString() + “”;
if(cb_three.isChecked())choose += cb_three.getText().toString() + “”;
Toast.makeText(this,choose,Toast.LENGTH_SHORT).show();
}
}
2.自定义点击效果
虽然5.0后的RadioButton和Checkbox都比旧版本稍微好看了点 , 但是对于我们来说 可能还是不喜欢或者需求 , 需要自己点击效果!实现起来很简单 , 先编写一个自定义 的selctor资源 , 设置选中与没选中时的切换图片~!
实现效果图如下:
PS:这里素材的原因 , 有点小…
<?xml version=”1.0″ encoding=”utf-8″?>
<selector xmlns:android=”http://schemas.android.com/apk/res/android”>
<item
android:state_enabled=”true”
android:state_checked=”true”
android:drawable=”@mipmap/ic_checkbox_checked”/>
<item
android:state_enabled=”true”
android:state_checked=”false”
android:drawable=”@mipmap/ic_checkbox_normal” />
</selector>
写好后 , 我们有两种方法设置 , 也可以说一种吧!你看看就知道了~


以上关于本文的内容,仅作参考!温馨提示:如遇健康、疾病相关的问题,请您及时就医或请专业人士给予相关指导!

「四川龙网」www.sichuanlong.com小编还为您精选了以下内容,希望对您有所帮助: