一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Android中实现单选按钮的效果

时间:2015-07-01 编辑:简简单单 来源:一聚教程网

我们经常在淘宝下单时,会选择尺寸,样式,在一排按钮里设置只能选中一个,我们知道按钮Button是不能唯一选中的,当我们点击一排按钮时我们会发现这一排全会被选择。下面我们就来看一下怎么样实现只选中一个按钮。

首先根据获取的数据动态生成一排按钮。

List sizeEntityList=productEntity.getSize();
if(sizeEntityList!=null&&sizeEntityList.size()>0) {
    for (int i = 0; i < sizeEntityList.size(); i++) {
       final SizeEntity size=sizeEntityList.get(i);
       final Button button = new Button(getContext());
       button.setId(i);
       button.setText(sizeEntityList.get(i).getName());
       button.setBackgroundResource(R.drawable.shape_round_corner_0_stroke_bg_grey);
       button.setTextSize(10);
       mSizeContent.addView(button, Math.min(1, mSizeContent.getChildCount()));
   }
}

下面来处理点击事件:

button.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View view) {
          for (int j = 0; j < mSizeContent.getChildCount(); j++) {
               final Button mbutton = (Button) mSizeContent.getChildAt(j);
               if (button == mbutton) {
                  mbutton.setBackgroundResource(R.color.red);
                  mbutton.setTextColor(getResources().getColor(R.color.white));
               } else {
                  mbutton.setBackgroundResource(R.drawable.shape_round_corner_0_stroke_bg_grey);
                  mbutton.setTextColor(getResources().getColor(R.color.black));
                }
            }
 
       }
});

一个raid例子


xml文件

       xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    tools:context=".MainActivity"
    android:orientation="vertical">

            android:id="@+id/txt"
        android:layout_
        android:layout_
        android:text="您的性别为"/>
   
            android:id="@+id/sex"
        android:layout_
        android:layout_>
                    android:id="@+id/male"
            android:text="男"/>
                    android:id="@+id/female"
            android:text="女"/>
       
   


java文件

public class MainActivity extends Activity {
private TextView txt=null;
private RadioGroup sex=null;
private RadioButton male=null;
private RadioButton female=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.txt=(TextView) super.findViewById(R.id.txt);
this.sex=(RadioGroup) super.findViewById(R.id.sex);
this.male=(RadioButton) super.findViewById(R.id.male);
this.female=(RadioButton) super.findViewById(R.id.female);
this.sex.setOnCheckedChangeListener(new OnCheckedChangeListenerImp());
}
private class OnCheckedChangeListenerImp implements OnCheckedChangeListener{

public void onCheckedChanged(RadioGroup group, int checkedId) {
String temp=null;
if(MainActivity.this.male.getId()==checkedId){
temp="男";
}
else if(MainActivity.this.female.getId()==checkedId){
temp="女";
}
MainActivity.this.txt.setText("您的性别是"+temp);
}
}

}

热门栏目