ListView持有人与复选框

时间:2014-05-17 00:12:31

标签: android android-layout listview android-listview android-arrayadapter

我正在使用自定义布局 arrayAdapter 开发应用。我的自定义布局由1个ImageView,2个textView和1个复选框组成。

将图像文件和文本存储在values.xml的string.xml中。

enter image description here

所以我的问题是当我点击复选框时我无法获得正确的位置(索引)。我只想要一个Toast消息出现在复选框上的位置。

e.g。如果我点击 meme3复选框会出现 2

让我们看一些代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Resources res = getResources();
    titles = res.getStringArray(R.array.titles);
    descriptions = res.getStringArray(R.array.descriptions);
    list = (ListView) findViewById(R.id.listView1);

    MyAdapter adapter = new MyAdapter(this, titles, images, descriptions);
    list.setAdapter(adapter);
}

这是我的ArrayAdapter

class MyAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
    Context context;
    int[] images;
    String[] titlesArray, descrptionArray;

MyAdapter(Context context, String[] titles, int[] images, String[] description) {
    super(context, R.layout.single_row, R.id.textView1, titles);
    this.context = context;
    this.images = images;
    this.titlesArray = titles;
    this.descrptionArray = description;
}

class MyViewHolder {
    ImageView myImage;
    TextView myTitle;
    TextView myDescription;
    CheckBox box;

    MyViewHolder(View v) {
        myImage = (ImageView) v.findViewById(R.id.imageView1);
        myTitle = (TextView) v.findViewById(R.id.textView1);
        myDescription = (TextView) v.findViewById(R.id.textView2);
        box = (CheckBox) v.findViewById(R.id.checkBox1);
    }
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    MyViewHolder holder = null;
    if (row == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(R.layout.single_row, parent, false);
        holder = new MyViewHolder(row);
        row.setTag(holder);
    } else {
        holder = (MyViewHolder) row.getTag();
    }
    holder.myImage.setImageResource(images[position]);
    holder.myTitle.setText(titlesArray[position]);
    holder.myDescription.setText(descrptionArray[position]);
    holder.box.setOnCheckedChangeListener(this);
    return row;
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if(isChecked){
        int position = (Integer)buttonView.getTag();
        Toast.makeText(getContext(), ""+position, Toast.LENGTH_SHORT).show();
    }
}
}

我的清单有20个项目。现在如果我选中一个复选框,应用程序会自动选择其他2个其他复选框!请帮助!

1 个答案:

答案 0 :(得分:1)

您可以在复选框上将位置设置为标记。

holder.box.setTag(position);

使用以下内容在听众中检索:

int position = (Integer)buttonView.getTag();