繁体   English   中英

在ListView上获取复选框项时出现问题

[英]Problem getting Checkbox items on the ListView

我在setListAdapter之前使用了simple_multiple_choice来创建带有复选框的listview。

然后我做了确定尺寸并选择了职位:

SparseBooleanArray checked = list.getCheckedItemPositions();
cont = list.getCheckedItemPositions().size();

if (checked.get(i)) 
{
...

但是现在我需要对布局进行更多控制,因此我在xml上执行listview,如下所示:

<listview>
<checkboxes id=.../>
</listview>

对这些ID使用setAdapter。

正确填充了listview(与以前一样), 问题是 ,现在SparseBooleanArray不起作用。 Thar变量'cont',给我0,'checked'为null。

确保“列表”正确:

int len = list.getCount();

它给了我正确的价值。

有什么问题?

您需要实现自定义列表适配器。

public class YourAdapterName extends BaseAdapter{

private Context mContext;
private DataType mValuestoShow;//Use your DataType to pass values to adapter. 

/**
 * Constructor to be called to initialize adapter with values.
 * @param context
 * @param vector
 */
public YourAdapterName(Context context, DataType data){
    mContext = context;
    mValuestoShow = vector;
}

public int getCount() {
    if(null != mValuestoShow){
        return mValuestoShow.size();
    }
    return 0;
}

public Object getItem(int position) {
    if(position < mValuestoShow.size())
        return  mValuestoShow.get(position);
    else
        return null;
}

public long getItemId(int position) {
    return 0;
}



public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder ;
    if(convertView == null){
        LayoutInflater li =(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = li.inflate(R.layout.your_layout, null);
        holder = new ViewHolder();
        holder.txt_name = (TextView) convertView.findViewById(R.id.name_txt);
        holder.checkBox = (Checkbox) convertView.findViewById(R.id.checkbox);
        convertView.setTag(holder);
    }else{
        holder = (ViewHolder) convertView.getTag();
    }

    holder.txt_name.setText(getItem(position).toString());
    holder.checkBox    // Do your task with checkbox.
    return convertView;
}

class ViewHolder {
    TextView txt_name;
    Checkbox checkBox;
}

}

your_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width = "fill_parent"
    android:layout_height = "wrap_content"
    android:padding = "10dp" >

<TextView
    android:id = "@+id/txt_type1"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content" />

<CheckBox
    android:id = "@+id/checkbox"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:layout_alignParentRight="true" />

</RelativeLayout>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM