android - 在 Android 的 ListView 中操作 RadioButton

标签 android listview radio-button

我使用自定义适配器创建了一个自定义 ListView,每行都带有 radioButton。我想在检查其父 View (列表项)时以编程方式检查单选按钮,然后取消选中其他 ListView 项目中的其他 RadioButtons。谁能给我解决方案?

更新

这是我的 getView()

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LinearLayout v = null;

    final Item i = items.get(position);

    EntryItem ei = (EntryItem) i;
    v = (LinearLayout) vi.inflate(R.layout.list_item_entry, null);
    final TextView title = (TextView) v
                    .findViewById(R.id.list_item_entry_title);
    final TextView subtitle = (TextView) v
                    .findViewById(R.id.list_item_entry_summary);


    RadioButton radioButton = new RadioButton(context);
    radioButton.setFocusable(false);
    radioButton.setFocusableInTouchMode(false);
    v.addView(radioButton); 

    if (title != null)
                title.setText(ei.title);
    if (subtitle != null)
                subtitle.setText(ei.subtitle);


    convertView = v;
    return convertView;
}

最佳答案

如果要选择单个项目,可以使用一个int变量,用-1初始化;

int index =-1;

在getView方法中添加一行:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LinearLayout v = null;

    final Item i = items.get(position);

    EntryItem ei = (EntryItem) i;
    v = (LinearLayout) vi.inflate(R.layout.list_item_entry, null);
    final TextView title = (TextView) v
                    .findViewById(R.id.list_item_entry_title);
    final TextView subtitle = (TextView) v
                    .findViewById(R.id.list_item_entry_summary);


    RadioButton radioButton = new RadioButton(context);
    radioButton.setFocusable(false);
    radioButton.setFocusableInTouchMode(false);
    radioButton.setChecked(index==position);
    radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {                       
                    @Override
                    public void onCheckedChanged(CompoundButton arg0, boolean arg1) {

                    }
                });
                v.addView(radioButton);
            } 
            if (title != null)
                title.setText(ei.title);
            if (subtitle != null)
                subtitle.setText(ei.subtitle);
        }

    convertView = v;
    return convertView;
}

并在监听器的 OnItemClick 方法中,执行:

index=position;
adapter.notifyDataSetInvalidated();

关于android - 在 Android 的 ListView 中操作 RadioButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11664077/

相关文章:

android - Eclipse:无法优先设置sdk路径

android - 在 OpenCV 中将位图转换为垫子,反之亦然

java - 拖拽时, stub 中的 ListView 会变黑。

android - 自定义选择 Intent 排除我自己的 Activity

android - onSaveInstanceState() 应该在 onDestroy() 而不是 onStop()?

android - Eclipse IDE 中缺少 ListView 组件

jQuery 移动 CSS : Why aren't my items styled properly?

ios - 如何在表格 View 中一次选择单选按钮

javascript - 检测jquery中2组单选按钮的选择

xaml - 一旦选中,如何防止RadioButton被取消选中?