ListView设置自定义检查图像

时间:2014-08-19 15:22:46

标签: android listview android-imageview

我有一个ListView,并且有3行。

我的功能是当我点击第一行时,第一行包含检查图像,并且显示为true。和其他2行检查图像可见假。

在此代码中,只有最后一行的检查图像可见。 代码:

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO Auto-generated method stub

            TextView text = (TextView) view.findViewById(R.id.label);

            String selectItem = (String) text.getText();

            for (int i = 0; i < listView.getCount(); i++) {

                ImageView checkImg = (ImageView) view
                        .findViewById(R.id.select_img);

                //checkImg[position];
                //checkImg.setVisibility(View.VISIBLE);

                if (i == position) {
                     Log.e("Num", position + "Hi" + i + "");
                     checkImg.setVisibility(View.VISIBLE);

                } else {
                    checkImg.setVisibility(View.GONE);
                }

            }

            // String product = ((TextView) view).getText().toString();

        }
    });

谢谢, Dharmik

1 个答案:

答案 0 :(得分:1)

您需要创建自定义适配器

public class MAdapter extends ArrayAdapter<String>{
private LayoutInflater  inflater;
private Context         context;
 int selectedPosition = -1;
List<String> objects;
public MAdapter(Context ctx,List<String> objects) {
    super(ctx, objects);
    inflater = LayoutInflater.from( ctx );
    this.context=ctx;
    this.objects=objects;
}

 @overwrite
 public int getCount(){
     return objects.length;
 }
 public View getView ( int position, View convertView, ViewGroup parent ) {
    LayoutInflater inflater = (LayoutInflater)         context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.your_row_for_items, parent,false);


    ImageView selected = (ImageView) convertView.findViewById(R.id.s);
    if(selectedPosition == position){
        selected.setVisibility(View.VISIBLE);
    }else
        selected.setVisibility(View.INVISIBLE);

    return convertView;
}

}  

和on onItemCLick

MAdapter = adapter = new MAdapter(this,yourArray);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
        // TODO Auto-generated method stub

            adapter.selectedPosition = position;
            adapter.notifyDataSetChanged();

        }

        // String product = ((TextView) view).getText().toString();

    }
});