onClick已解雇,但未获得正确的listview项目

时间:2016-01-27 15:11:59

标签: android android-layout listview onclick

我的listview项目有这个布局:

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

    <ImageView
        android:id="@+id/cartIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginRight="10dp"
        android:onClick="addToCartClick"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/itemName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_toRightOf="@id/cartIcon"
        android:text="Filé Mignon"
        android:textAppearance="@android:style/TextAppearance.Small"
        android:typeface="normal" />

    <TableLayout
        android:id="@+id/tableInfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/itemName"
        android:layout_toRightOf="@id/cartIcon"
        android:weightSum="3">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/qtyText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Qtd"
                android:textAlignment="center"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <TextView
                android:id="@+id/priceText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Preço"
                android:textAlignment="center"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <TextView
                android:id="@+id/totalText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Total"
                android:textAlignment="center"
                android:textAppearance="?android:attr/textAppearanceSmall" />

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/qty"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="2 Kg"
                android:textAlignment="center"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <TextView
                android:id="@+id/price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="R$ 75,00"
                android:textAlignment="center"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <TextView
                android:id="@+id/total"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="R$ 150,00"
                android:textAlignment="center"
                android:textAppearance="?android:attr/textAppearanceSmall" />

        </TableRow>
    </TableLayout>

</RelativeLayout>

对于ImageView的onClick方法:

android:onClick="addToCartClick"

点击ImageView时onClick会正常触发,但无法获得正确的视图 我想在onClick发生时替换图像,它取代了,但不仅仅是这个ImageView。它取代了其他几个。这似乎是随机的 onClick的代码如下:

 public void addToCartClick(View view) {
    ImageView img = (ImageView) view;
    img.setImageResource(R.drawable.cart_add);
}  

适配器代码:

public class ShopListAdapter extends ArrayAdapter<ShopListItem> {

Context context;
int resource;
ShopListItem[] objects;

public ShopListAdapter(Context context, int resource, ShopListItem[] objects) {
    super(context, resource, objects);

    this.context = context;
    this.resource = resource;
    this.objects = objects;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {
        // inflate the layout
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        convertView = inflater.inflate(resource, parent, false);
    }

    // object item based on the position
    ShopListItem item = objects[position];

    // get the TextView and then set the text (item name) and tag (item ID) values
    TextView itemName = (TextView) convertView.findViewById(R.id.itemName);
    itemName.setText(item.itemName);

    TextView qty = (TextView) convertView.findViewById(R.id.qty);
    qty.setText(item.quantity + "kg");

    TextView price = (TextView) convertView.findViewById(R.id.price);
    price.setText("R$" + item.price);

    TextView total = (TextView) convertView.findViewById(R.id.total);
    total.setText("R$" + item.total);

    return convertView;
}

}

我错过了什么?

5 个答案:

答案 0 :(得分:1)

ListView项目视图由ListView回收 您应该在Adapter#getView中将默认图像资源设置为ImageView。

<强> EDITED 你可以使用标签。

 public void addToCartClick(View view) {
    ImageView img = (ImageView) view;
    img.setImageResource(R.drawable.cart_add);
    ((MyAdapter.MyItem)img.getTag()).addedCart = true;
}  

你的Adapter类。

public class MyAdapter extends BaseAdapter {
    public static class MyItem {
        public boolean addedCart;

        public MyItem(boolean addedCart) {
            this.addedCart = addedCart;
        }
    }

    public List<MyItem> itemList = new ArrayList<>();
    public MyAdapter() {
        final ArrayList<MyItem> myItems = new ArrayList<>();
        // your list size
        for (int i = 0; i < 10; i++) {
            myItems.add(new MyItem(false));
        }
        this.itemList = myItems;
    }

    @Override
    public int getCount() {
        return 10;
    }

    @Override
    public Object getItem(int position) {
        return itemList.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Inflate View

        imageView.setTag(getItem(position));
        if (((MyItem)getItem(position)).addedCart){
            imageView.setImageResource(R.drawable.cart_add);
        }else{
            imageView.setImageResource(R.drawable.default_image);
        }
        return view;
    }
}

答案 1 :(得分:1)

在ShopListItem类中取一个布尔值 -

  public boolean isSelected; 

然后检入getView方法并根据此布尔值设置其图像,因此当您滚动列表视图时,图像将设置为您之前选择的特定图像视图 -

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {
        // inflate the layout
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        convertView = inflater.inflate(resource, parent, false);
    }

    // object item based on the position
    ShopListItem item = objects[position];

    // get the TextView and then set the text (item name) and tag (item ID) values
    TextView itemName = (TextView) convertView.findViewById(R.id.itemName);
    itemName.setText(item.itemName);

    TextView qty = (TextView) convertView.findViewById(R.id.qty);
    qty.setText(item.quantity + "kg");

    TextView price = (TextView) convertView.findViewById(R.id.price);
    price.setText("R$" + item.price);

    TextView total = (TextView) convertView.findViewById(R.id.total);
    total.setText("R$" + item.total);

    ImageView img = (ImageView) view.findViewById(R.id.cartIcon);
    img.setTag(position);

    if ( objects.isSelected ){

       img.setImageResource(R.drawable.cart_add);
    }else{
        // you can set default image here
    }
  }

    return convertView;
}

并添加此代码 -

 public void addToCartClick(View view) {
    object.get( Integer.parseInt(view.getTag()) ).isSelected = true;
    notifyDatasetChanged();
 }  

答案 2 :(得分:0)

您应该使用onClick方法定义getView逻辑。你正在为它定义一个点击监听器,但它还不知道该位置。从getView,您可以传递项目的位置以查看正确的项目

修改:如果您要更改行本身,请按照this链接

进行操作

答案 3 :(得分:0)

你是否重写public boolean hasStableIds()才能返回true?听起来像是ListView中的某些项可能具有相同的ID。如果要覆盖public long getItemId(int position),请确保该函数不能为不同的ListView项返回相同的long。您还应该设置public boolean hasStableIds()以返回false

如果这不起作用,请尝试从XML文件中删除android:onClick="addToCartClick",然后在ListAdapter的public View getView (int position, View convertView, ViewGroup parent)函数中添加一个OnClickListener,如下所示:

imageView.setOnClickListener(new View.OnClickListener() {
    void onClick(View v) {
        addToCartClick(imageView)
    }
});

答案 4 :(得分:0)

全力以赴,我找到了解决方案:

我的新getView带有@Mohamed建议的视图持有者模式:

Nothing uploaded

onClick方法:

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder viewHolder;
    // object item based on the position
    final ShopListItem item = objects[position];

    if (convertView == null) {
        // inflate the layout
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        convertView = inflater.inflate(resource, parent, false);

        viewHolder = new ViewHolder();
        viewHolder.itemName = (TextView) convertView.findViewById(R.id.itemName);
        viewHolder.qty = (TextView) convertView.findViewById(R.id.qty);
        viewHolder.price = (TextView) convertView.findViewById(R.id.price);
        viewHolder.total = (TextView) convertView.findViewById(R.id.total);
        viewHolder.img = (ImageView) convertView.findViewById(R.id.cartIcon);

        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    // get the TextView and then set the text (item name) and tag (item ID) values

    viewHolder.itemName.setText(item.itemName);

    viewHolder.qty.setText(item.quantity + "kg");

    viewHolder.price.setText("R$" + item.price);

    viewHolder.total.setText("R$" + item.total);

    //Here's the trick
    viewHolder.img.setTag(R.string.tag_adapter, this);
    viewHolder.img.setTag(R.string.tag_item, item);

    if(!item.finished)
        viewHolder.img.setImageResource(R.drawable.ic_launcher);
    else
        viewHolder.img.setImageResource(R.drawable.cart_add);
    //End Here's the trick
    return convertView;
}

并且,正如@ARMV所建议的,创建了一个标志&#34;完成&#34;检查使用哪个图像。 这样就不需要在适配器中放置onClickListener。并使用适配器和当前项目设置标签我可以使用多个列表视图 也可以使用Men Taka建议的标签 它运作得很好。
谢谢大家!