Android如何用checkBox实现单选

2024-05-24 23:18
文章标签 实现 android 单选 checkbox

本文主要是介绍Android如何用checkBox实现单选,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

第一次写博客,不足的地方多多提出,会努力改进,谢谢!(ps:图片上传了不知道怎么看不见。。。)

1.布局文件activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
         android:orientation="vertical" >

           <!-- listView -->
           <ListView
             android:id="@+id/lv_single_list"
             android:layout_width="fill_parent"
             android:layout_height="400dp"
             android:cacheColorHint="#00000000"
            android:clickable="true"
            android:descendantFocusability="blocksDescendants"
            android:divider="#f80"
            android:dividerHeight="1.0dip"
            android:fadingEdge="none"
            android:fastScrollEnabled="true"
            android:scrollingCache="false" />
</LinearLayout>

2. listviewitem.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/tv_zxing_section_sequence"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tv_zxing_sectionname"
        android:layout_width="210dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:textSize="14sp" />

    <CheckBox
        android:id="@+id/item_cb_section"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="5dp"
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false" />

</LinearLayout>


3.MainActivity.java



    private ListView listView;//listView 控件
    
    private Map<Integer, Boolean> isSelected;//判断CheckBox是否选中
    
    private List beSelectedData = new ArrayList();    //存放选中checkbox的集合
    
    ListAdapter adapter;//适配器
    
    private List cs = null;//显示listview数据
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) this.findViewById(R.id.lv_single_list);
        cs  = new ArrayList();
        cs.add("aaaaaa");
        cs.add("bbbbbb");
        cs.add("cccccc");
        cs.add("dddddd");
        cs.add("eeeeee");
        cs.add("ffffff");
        initList();
    }
    
    void initList(){
        
        if (cs == null || cs.size() == 0)
            return;
        if (isSelected != null)
            isSelected = null;
        isSelected = new HashMap<Integer, Boolean>();
        for (int i = 0; i < cs.size(); i++) {
            isSelected.put(i, false);
        }
        // 清除已经选择的项
        if (beSelectedData.size() > 0) {
            beSelectedData.clear();
        }
        adapter = new ListAdapter(this, cs);
        listView.setAdapter(adapter);
     

    /**
     * The list allows up to one choicelistview 选中样式
     */

  listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        adapter.notifyDataSetChanged();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
               Log.i("map", cs.get(position).toString());
            }
        });
        
    }
   

//适配器
    class ListAdapter extends BaseAdapter {

        private Context context;

        private List cs;

        private LayoutInflater inflater;//布局填充器

        public ListAdapter(Context context, List data) {
            this.context = context;
            this.cs = data;
            initLayoutInflater();
        }

        void initLayoutInflater() {
            inflater = LayoutInflater.from(context);
        }

        public int getCount() {
            return cs.size();
        }

        public Object getItem(int position) {
            return cs.get(position);
        }

        public long getItemId(int position) {
            return 0;
        }
    public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.listviewitem,null);
                holder = new ViewHolder();
                holder.checkBox = (CheckBox) convertView
                        .findViewById(R.id.item_cb_section);
                holder.tv_sequence = (TextView) convertView
                        .findViewById(R.id.tv_zxing_section_sequence);
                holder.tv_sectionname = (TextView) convertView
                        .findViewById(R.id.tv_zxing_sectionname);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }            
            holder.checkBox.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    // 当前点击的CheckBox
                    boolean cu = !isSelected.get(position);
                    // 先将所有的CheckBox置为FALSE
                    for(Integer p : isSelected.keySet()) {
                        isSelected.put(p, false);
                    }
                    // 再将当前选择CB的实际状态
                    isSelected.put(position, cu);
                    //通知改变
                    ListAdapter.this.notifyDataSetChanged();
                    beSelectedData.clear();
                    if(cu)
                        beSelectedData.add(cs.get(position));
                }
            });
            //控件内容
            holder.tv_sequence.setText(String.valueOf(position + 1));
            holder.tv_sectionname.setText(cs.get(position).toString());
            holder.checkBox.setChecked(isSelected.get(position));
            return convertView;
        }
    }
    /**
     * 就是一个持有者的类,他里面一般没有方法,只有属性,作用就是一个临时的储存器,
     * 把你getView方法中每次返回的View存起来,可以下次再用。
     * 这样做的好处就是不必每次都到布局文件中去拿到你的View,提高了效率
     * @author Administrator
     *
     */
    class ViewHolder {

        CheckBox checkBox;

        TextView tv_sequence;

        TextView tv_sectionname;

    }


源码地址:http://download.csdn.net/detail/u010904027/9140483


这篇关于Android如何用checkBox实现单选的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/999814

相关文章

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

c++ 类成员变量默认初始值的实现

《c++类成员变量默认初始值的实现》本文主要介绍了c++类成员变量默认初始值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录C++类成员变量初始化c++类的变量的初始化在C++中,如果使用类成员变量时未给定其初始值,那么它将被

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核