您的位置:首页 > 其它

gridview、listview适配器布局中带有checkbox实现的列表 checkbox只能有一项选中

2017-05-23 17:11 381 查看
先简单介绍下效果,手机话费充值、账户充值界面等有多个多选框选择套餐选项,默认只能有其中一项被选中,实现功能可以选择radiogroup和checkbox,但radiogroup在数据比较多的时候和布局比较复杂的情况下就不能很好的实现,所以采用checkbox来实现具体效果,请看效果图:



缴费金额可以由LinearLayout和relativelayout实现,但是充值套餐可能会有更多的套餐选择,为了更好的维护采用gridview来实现,整体思路就是gridview绑定的适配器中填充的convertview中只有一个checkbox,布局文件如下:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <CheckBox

        android:id="@+id/checkBox"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:padding="10dp"

        android:button="@null"

        android:background="@drawable/box_blue_checked_selector"

        android:layout_centerHorizontal="true"

        android:textSize="16sp"

        />

</RelativeLayout>

可以根据具体的项目需求,checkbox做具体的修改,适配器中的代码:

public class BoxAdapter extends BaseAdapter{

private LayoutInflater inflater;

public BoxAdapter(Context context){
inflater = LayoutInflater.from(context);
}

@Override
public int getCount() {
return mList == null ? 0 : mList.size();
}

@Override
public Object getItem(int position) {
return mList.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null){
convertView = inflater.inflate(R.layout.second_grid_item,null);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) convertView.getTag();
}
String s = mList.get(position);
viewHolder.checkBox.setText(s);

            viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override

                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    if (isChecked) {

                        buttonView.setClickable(false);

                        if (button != null) {

                            button.setChecked(false);

                        }

                    }else button.setClickable(true);

                    button = buttonView;

                }

            });

            return convertView;

        }

    }

public class ViewHolder{
public CheckBox checkBox;

public ViewHolder(View view){
checkBox = (CheckBox) view.findViewById(R.id.checkBox);
}
}

适配器中主要实现逻辑就是checkbox点击事件,定义一个临时compoundbutton对象变量,在checkboxonCheckedChangeListener中判断如果当前item被选中则把当前item设置成不可点击,实现反复点击当前item时一直保持被选中状态,然后判断button是否为空,第一次点击的时候button为空,所以buttonview赋值给button,如果button不为空说明点击了其它item,则把上一个点击的item置为没选中状态,将上一个item置成可点击状态,本文只是提供了思路,具体可根据项目需求进行修改
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐