Android:自定义可选ListView项

loe*_*sak 1 checkbox android listview

我几天来一直在寻找这个问题的解决方案.

我正在尝试创建一个自定义ListView列表项,可以选择进行批量编辑.这与列出收件箱中的电子邮件的Gmail应用程序类似,并允许您为操作选择一组电子邮件(删除,移动等).

我的要求是:

  • 必须有自定义的外观.android.R.layout.simple_list_item_ [checked | multiple_choice]布局不适合我正在寻找的东西
  • 我希望它能够使用给定的ListView#setChoiceMode和ListView#getCheckedItemPositions.CheckedTextView也不是.(另一种方法是没问题)
  • 我想在用户选择"编辑模式"时显示复选框
  • 我想修改类似于Android的选择模式的菜单选项

我试图在我的视图中添加自己的复选框,并为它设置一个OnClickListener,将列表项标记为选中/未选中,但这对我来说并不适用.

任何帮助表示赞赏; 即使它只让我90%的方式.

请记住,我正试图在Android 2.1及更高版本上使用它.

谢谢

aac*_*kin 6

看看这个链接

这是我为实现自己的自定义列表视图而阅读的资源.这对我真的很有帮助.我认为您需要在list_item.xml文件中添加一个复选框并更改布局属性.

您还需要在自定义适配器内的CheckBox对象onCheckedChanged上添加一个侦听器.

以下是自定义适配器的示例代码;

public class EntryAdapter extends ArrayAdapter<Entry> {

private Activity context;
private LayoutInflater inflater;
private ArrayList<Entry> entries;

public EntryAdapter(Activity context, ArrayList<Entry> objects) {
    super(context, R.layout.entry_item, objects);
    // TODO Auto-generated constructor stub
    this.context = context;
    this.entries = objects;
}

public View getView (int position,  View convertView, ViewGroup parent)
{
    View viewRow = convertView;
    if(viewRow == null)
    {                   
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);          
        viewRow = inflater.inflate(R.layout.entry_item , null, true);                       
    }

    Entry e = entries.get(position);
    if(e != null)
    {
        TextView aka = (TextView) viewRow.findViewById(R.id.authorTextView);
        TextView content = (TextView) viewRow.findViewById(R.id.entryContentTextView);

        if(aka != null && content != null){

            aka.setText(e.getAka());
            content.setText(e.getContent());
        }

    }


    return viewRow;

}
Run Code Online (Sandbox Code Playgroud)

}

在此代码中,没有事件侦听器.你首先应该做的是添加定义一个布尔类似的arraylist

ArrayList<boolean> selectedItems;
Run Code Online (Sandbox Code Playgroud)

之后,在getView方法中,您应该添加以下内容;

CheckBox cb = (CheckBox) findViewById(R.id.checkBoxId);
Run Code Online (Sandbox Code Playgroud)

之后,您应该在getView()方法中添加onCheckStateChanged侦听器

cb.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if ( isChecked )
        {
          // find out the item is selected or not and add to selected arraylist by using the position of the element
        }

}
});
Run Code Online (Sandbox Code Playgroud)

最后,你应该有getSelectedMethod,它返回所选项目的arraylist相对于它们的位置.

希望我理解这个问题,它对你有所帮助.