【问题标题】:android : checkbox problem?android:复选框问题?
【发布时间】:2011-11-02 19:03:36
【问题描述】:

我正在尝试选中列表中的所有复选框。为什么只有特定的复选框才正确。代码是:-

            ListView listview = (ListView)findViewById(R.id.listview1);
        for(int i=0; i < listview.getChildCount(); i++)
        {
            AbsoluteLayout itemLayout = (AbsoluteLayout)listview.getChildAt(i);
            CheckBox cb = (CheckBox)itemLayout.findViewById(R.id.checkBox1);
            if(cb.isChecked())
            {
                cb.setChecked(false);
            }
            else
            {
                cb.setChecked(true);
            }
        }

提前致谢。

【问题讨论】:

  • AbsoluteLayout 已弃用请勿使用
  • 如果你需要选择所有的复选框为什么 if else.just 写 cb.setChecked(true);

标签: java android checkbox android-listview


【解决方案1】:

不确定我是否完全理解这个问题..

但我相信:

CheckBox cb = (CheckBox)itemLayout.findViewById(R.id.checkBox1);

将始终返回相同的 CheckBox(ID 为 checkBox1),即使您的列表中有多个复选框。

【讨论】:

  • 不,不正确。仔细查看代码。它正在访问每个列表项作为布局并从中访问复选框。所以你不能说它一直是同一个复选框
  • 只有在他的列表视图顶部的复选框被修改。这就是我所指的。无需通过他的布局访问 CheckBox。每一行都代表一个整体的视图。
【解决方案2】:

试试:

   for(int i=0; i < listview.getChildCount(); i++)
        {
            CheckBox cb = (CheckBox)listview.getChildAt(i).findViewById(R.id.checkBox1);  //if the child views are properly populated in each row item then on this particular positon ChBox will be found and instantiated
            if(cb.isChecked())
            {
                cb.setChecked(false);
            }
            else
            {
                cb.setChecked(true);
            }
        }

【讨论】:

    【解决方案3】:

    您可以将其与两个按钮一起使用,例如 selectallunselectall

        public void checkallbtn_Click(View view)
    {
        ListView lv = (ListView)findViewById(R.id.backuplist);
        CheckBox cb;
        try
        {
            for(int i=0;i<lv.getCount();i++)
            {
                cb = (CheckBox)lv.getChildAt(i).findViewById(R.id.checkBox1);
                if(!cb.isChecked())
                {
                    cb.setChecked(true);
                }
            }
    
        }catch(Exception e) {e.printStackTrace();}
    }
    public void uncheckallbtn_Click(View view)
    {
        ListView lv = (ListView)findViewById(R.id.backuplist);
        try
        {
            for(int i=0;i<lv.getCount();i++)
            {
                CheckBox cb = (CheckBox)lv.getChildAt(i).findViewById(R.id.checkBox1);
                if(cb.isChecked())
                {
                    cb.setChecked(false);
                }
            }           
        }catch(Exception e) 
        {
            e.printStackTrace();
        }
    }
    

    希望这会对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 2016-04-26
      • 1970-01-01
      • 2016-10-10
      相关资源
      最近更新 更多