Android,可扩展列表中随机选中/取消选中的复选框

2023-12-06

Using 此可扩展列表复选框示例代码作为基线,我试图保存并维护复选框状态。但是,随机复选框正在被选中和取消选中(触发我的OnCheckedChangeListener使用新值)当我将它们滚动到视线之外时,最小化它们的组,甚至最小化/最大化附近的组!

public Object getChild(int groupPosition, int childPosition) {
    return colors.get( groupPosition ).get( childPosition );
}

public long getChildId(int groupPosition, int childPosition) {
    return (long)( groupPosition*1024+childPosition );  // Max 1024 children per group
}

public View getChildView(final int groupPosition, final int childPosition, 
        boolean isLastChild, View convertView, ViewGroup parent) {

    View v = null;
    if( convertView != null ) {
        v = convertView;
    } else {
        v = inflater.inflate(R.layout.child_row, parent, false); 
    }

    Color c = (Color)getChild( groupPosition, childPosition );

    TextView color = (TextView)v.findViewById( R.id.childname );
    if( color != null ) {
        color.setText( c.getColor() );
    }

    TextView rgb = (TextView)v.findViewById( R.id.rgb );
    if( rgb != null ) {
        rgb.setText( c.getRgb() );
    }

    CheckBox cb = (CheckBox)v.findViewById( R.id.check1 );
    cb.setChecked( c.getState() );
    cb.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            colors.get(groupPosition).get(childPosition).setState(isChecked);
            context.setColorBool(groupPosition, childPosition, isChecked);
            Log.d("ElistCBox2", "listitem position: " +groupPosition+"/"+childPosition+" "+isChecked);
        }
    });

    return v;
}

我不知道哪一段代码可能导致此问题,因此欢迎就此处包含的内容提供任何建议。我的代码仅在我尝试保存值时与原始代码不同。


我的猜测是,当您的适配器创建视图时,检查侦听器将在初始化复选框视图时被调用。 android 中的很多小部件都是这样工作的……当视图初始化时,监听器被调用。

我不知道为什么事情会这样工作,但可能是为了允许客户端代码以一致的方式初始化自身。例如,无论用户选中复选框还是将其初始化为选中状态,都运行相同的代码。

为了解决这个问题,您可以尝试执行一些操作,例如在侦听器类 impl 中设置一个标志,以允许您忽略第一次单击,例如,

cb.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {
        private void first = true;

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            if (first) {
              first = false;
              return;
            }

            colors.get(groupPosition).get(childPosition).setState(isChecked);
            context.setColorBool(groupPosition, childPosition, isChecked);
            Log.d("ElistCBox2", "listitem position: " +groupPosition+"/"+childPosition+" "+isChecked);
        }
    });

另外,请确保您正确地重用convertView在你的实施中getView()在你的适配器中。例如。,

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        view = inflater.inflate(R.layout.applications_item, null);
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android,可扩展列表中随机选中/取消选中的复选框 的相关文章

随机推荐