ViewHolder搞乱视图

问题描述 投票:3回答:1

我在listView中实现了ViewHolder和convertView。 我的listView由自定义适配器填充,其中包含预订列表。 当我点击某个项目时,一个不可见的布局从右向左滑动,以显示按钮。 我可以通过点击一个关闭按钮来解除这个重叠的布局,以便再次隐藏它。 在这个重叠的布局上,我有一个删除按钮,这使我可以删除该项目。 到现在为止还挺好。 当我擦除项目时项目按预期消失,然后重新加载适配器。 下面的项目采用已删除项目的位置,但仍然不可见。 我知道它在这里,因为我仍然可以点击该项目来触发覆盖的视图。 所以ovelaying视图是可见的,但不是项目。 我不知道为什么会这样。 我怀疑ViewHolder对此行为负责,但我找不到解决方案。 谢谢您的帮助。

观看视频:http: //youtu.be/KBGEvbUq-V0

我的预订课程:

public class BookingsListFragment extends Fragment {

private final String SHOP_NAME_KEY = "ShopName";
private final String SHOP_ADDRESS_KEY = "ShopAddress";
public static int mSelectedItem = -1;
private static ListView mBookingsListView;
private static BookingsListViewAdapter mBookingsListViewAdapter;
private static ArrayList<Booking> mBookings;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(getActivity()));
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.bookings_list_fragment, container, false);
    configureListView(view);
    return view;
}

@Override
public void onResume() {
    super.onResume();
    mSelectedItem = -1;
}

private void configureListView(View view) {
    mBookings = BookingsHandler.getBookings();
    mBookingsListView = (ListView) view.findViewById(R.id.bookingsListView);
    mBookingsListViewAdapter = new BookingsListViewAdapter();
    mBookingsListView.setAdapter(mBookingsListViewAdapter);
    mBookingsListView.setTextFilterEnabled(true);
}

public static void updateBookingsListView(ArrayList<Booking> mBookingsList){
    mBookings = mBookingsList;
    mBookingsListViewAdapter.notifyDataSetChanged();
}


static class ViewHolder {
    LinearLayout bookingItemLL;
    RelativeLayout optionsOverlay;
    TextView productName;
    TextView price;
    TextView shopName;
    TextView endDate;
    ImageView productImage;
    LinearLayout placeholderLL;
    Button cancelBooking;
    Button displayDirections;
    Button callShop;
    ImageView discardOverlay;
}


private class BookingsListViewAdapter extends BaseAdapter {

    private static final int TYPE_ITEM = 0;
    private static final int TYPE_PLACEHOLDER = 1;

    @Override
    public int getCount() {
        if (mBookings != null)
            return mBookings.size();
        else
            return 1;
    }

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

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

    @Override
    public int getItemViewType(int position) {
        // Define a way to determine which layout to use
        if (mBookings != null && mBookings.size() > 0)
            return TYPE_ITEM;
        else
            return TYPE_PLACEHOLDER;
    }

    @Override
    public int getViewTypeCount() {
        return 2; // Number of different layouts
    }

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

        int type = getItemViewType(position);

        final ViewHolder holder;

        if(convertView == null) {
            holder = new ViewHolder();

            switch (type){
                case TYPE_ITEM :
                    convertView = LayoutInflater.from(getActivity()).inflate(R.layout.bookings_item,     null);

                    holder.bookingItemLL = (LinearLayout) convertView.findViewById(R.id.bookingItemLL);
                    holder.optionsOverlay = (RelativeLayout) convertView.findViewById(R.id.bookingOptionsOverlay);
                    holder.productName = (TextView) convertView.findViewById(R.id.bookingProductName);
                    holder.price = (TextView) convertView.findViewById(R.id.bookedProductPrice);
                    holder.shopName = (TextView) convertView.findViewById(R.id.bookingShopName);
                    holder.endDate = (TextView) convertView.findViewById(R.id.bookingEndDate);
                    holder.productImage = (ImageView) convertView.findViewById(R.id.bookedProductImage);
                    holder.displayDirections = (Button) convertView.findViewById(R.id.routeShop);
                    holder.cancelBooking = (Button) convertView.findViewById(R.id.cancelBooking);
                    holder.callShop = (Button) convertView.findViewById(R.id.callShop);
                    holder.discardOverlay = (ImageView) convertView.findViewById(R.id.discardOverlay);

                    break;
                case TYPE_PLACEHOLDER :
                    convertView = LayoutInflater.from(getActivity()).inflate(R.layout.booking_placeholder, null);
                    holder.placeholderLL = (LinearLayout) convertView.findViewById(R.id.placeHolderLL);
                    break;
            }
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }

        if(type == 0) {

            if(position == mSelectedItem){
                holder.optionsOverlay.setVisibility(View.VISIBLE);
                configureOverlayButtons(holder);
            }

            holder.bookingItemLL.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mSelectedItem != position && mSelectedItem != -1){
                        View item = mBookingsListView.getChildAt(mSelectedItem - mBookingsListView.getFirstVisiblePosition());
                        if(item != null){
                            RelativeLayout overlayOptions = (RelativeLayout) item.findViewById(R.id.bookingOptionsOverlay);
                            overlayOptions.setVisibility(View.GONE);
                        }
                    }
                    Animation slideInAnimation = AnimationUtils.loadAnimation(getActivity(),    R.anim.booking_options_overlay_animation);
                    holder.optionsOverlay.startAnimation(slideInAnimation);
                    holder.optionsOverlay.setVisibility(View.VISIBLE);
                    mSelectedItem = position;
                    configureOverlayButtons(holder);
                }
            });

            final Booking booking = mBookings.get(position);
            holder.productName.setText(booking.getName().toUpperCase());
            holder.price.setText("Prix lors de la réservation : " + String.format("%.2f", Float.valueOf(booking.getPrice())) + " €");
            holder.shopName.setText(booking.getShopName());
            holder.endDate.setText(booking.getEndDate());
            holder.productImage.setScaleType(ImageView.ScaleType.CENTER_CROP);

            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.product_placeholder)
                    .showImageOnFail(R.drawable.product_no_image_placeholder)
                    .cacheInMemory(true)
                    .cacheOnDisk(true)
                    .build();
            ImageLoader imageLoader = ImageLoader.getInstance();
            imageLoader.displayImage(BeeWylApiClient.getImageUrl(booking.getImageURL()),holder.productImage, options);
        }
        if(type == 1){
            holder.placeholderLL.setLayoutParams(BeeWylHelper.getPlaceHolderSizeForFreeScreenSpace(getActivity(),0));
        }
        return convertView;
    }


    private void configureOverlayButtons(final ViewHolder holder){

        holder.cancelBooking.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder ab = new AlertDialog.Builder(getActivity());
                ab.setMessage("Annuler la réservation ?").setPositiveButton("Oui", dialogClickListener)
                        .setNegativeButton("Non", dialogClickListener).show();
            }
        });

        holder.displayDirections.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                launchMapActivity();
            }
        });

        holder.callShop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                launchDialer();
            }
        });

        holder.discardOverlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Animation hideOverlayAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.booking_overlay_dismiss);
                holder.optionsOverlay.startAnimation(hideOverlayAnimation);
                holder.optionsOverlay.setVisibility(View.GONE);
                holder.optionsOverlay.clearAnimation();
            }
        });
    }


    private void sendCancelBookingToAPI(String id_booking) throws JsonProcessingException {

            BeeWylApiClient.cancelBooking(id_booking, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    try {
                        Log.v("xdebug CANCEL", new String(bytes, "UTF_8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                    Log.v("xdebug CANCEL ERROR", String.valueOf(throwable));
                }
            });
    }

    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    Animation hideOverlayAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.booking_overlay_dismiss);
                    mBookingsListView.getChildAt(mSelectedItem-mBookingsListView.getFirstVisiblePosition()).startAnimation(hideOverlayAnimation);
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            try {
                                sendCancelBookingToAPI(mBookings.get(mSelectedItem).getId());
                            } catch (JsonProcessingException e) {
                                e.printStackTrace();
                            }
                            mBookings.remove(mSelectedItem);
                            mSelectedItem = -1;
                            updateBookingsListView(mBookings);
                        }
                    }, hideOverlayAnimation.getDuration());
                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    dialog.cancel();
                    break;
            }
        }
    };       
}

}

并且项目膨胀:

<?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:paddingTop="5dp"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
    >


<LinearLayout
        android:id="@+id/bookingItemLL"
        android:layout_width="match_parent"
        android:layout_height="151dp"
        android:orientation="horizontal"
        android:weightSum="100"
        android:background="@drawable/product_item_rectangle"
        >

    <ImageView
            android:id="@+id/bookedProductImage"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:background="@android:color/white"
            android:src="@drawable/nivea"
            />


    <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center_vertical"
            >
        <TextView
                android:id="@+id/bookingProductName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="BRUME NIVEA"
                android:textColor="@color/ProductsBlue"
                android:textSize="16dp"
                android:textStyle="bold"
                />

        <TextView
                android:id="@+id/bookedProductPrice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Prix lors de la réservation : 24,90€"
                android:textSize="12dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:textColor="@color/ProductsBlue"                        android:layout_gravity="left"
                />

        <TextView
                android:id="@+id/bookingShopName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text="Magasin"
                android:textSize="12dp"
                android:textColor="@color/ProductsBlue"
                />

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text="Réservé jusqu'au"
                android:textSize="12dp"
                android:textColor="@color/ProductsBlue"                        />

        <TextView
                android:id="@+id/bookingEndDate"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="-"
                android:textSize="12dp"
                android:textColor="@color/ProductsBlue"                        />
    </LinearLayout>
</LinearLayout>


<RelativeLayout android:id="@+id/bookingOptionsOverlay"
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:background="#EEFFFFFF"
                android:visibility="gone">


    <ImageView
            android:id="@+id/discardOverlay"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:src="@drawable/ic_discard_booking_overlay"
            android:padding="5dp"
            />


    <Button android:id="@+id/callShop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="APPELER"
            android:layout_weight="1"
            android:background="#00000000"
            android:drawableTop="@drawable/booking_call"
            android:textColor="@color/ProductsBlue"
            android:textSize="14dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:drawablePadding="20dp"
            android:layout_marginLeft="20dp"
            />
    <Button android:id="@+id/cancelBooking"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ANNULER"
            android:layout_weight="1"
            android:background="#00000000"
            android:drawableTop="@drawable/booking_cancel"
            android:textColor="@color/ProductsBlue"
            android:textSize="14dp"
            android:layout_centerInParent="true"
            android:drawablePadding="20dp"

            />
    <Button android:id="@+id/routeShop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ITINERAIRE"
            android:layout_weight="1"
            android:background="#00000000"
            android:drawableTop="@drawable/booking_route"
            android:textColor="@color/ProductsBlue"
            android:textSize="14dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:drawablePadding="20dp"
            android:layout_marginRight="20dp"
            />

    </RelativeLayout>

</RelativeLayout>
android listview convertview android-viewholder
1个回答
2
投票

您的问题来自重新使用convertView。

当上一个项目单击时,OnClickListener被激活,并且在那里项目的可见性被设置为GONE。 后来这个视图被回收并传递给getView()作为convertView。 因为您正在重新使用它而不重置所做的任何更改,所以您现在正在使用View来查找未处于已知状态的新项目。 在使用convertView之前,您应该确保撤消任何更改。

快速解决方法是不重用传递给getView()的convertView。 因此,在您的代码中,您检查是否可以重新使用convertView:

if(convertView == null)

破坏检查以确定事情是否开始起作用:

if(true)

如果这样做,您可能需要正确修复它。

在上述检查的else子句中,您将从标记中获取项目持有者。 同时撤消OnClickListeners可能进行的任何更改。 您希望以已知状态的新项目的View开头。 您应该明确初始化它。 例如:

if(convertView == null) {
    // ... snipped all the initialization ...
} else {
    holder = (ViewHolder)convertView.getTag();
    convertView.setVisibility(View.VISIBLE);
}

更新

我从来没有使用过'异类'适配器,所以我无法真正回答为什么“convertView重用了覆盖视图而不是我的项目的根视图。” Adapter.getView()的Android开发人员文档说明了convertView参数:

如果可能的话,重用旧视图。 注意: 在使用之前 ,应检查此视图是否为非null 且类型是否合适 。 如果无法转换此视图以显示正确的数据,则此方法可以创建新视图。 异构列表可以指定它们的视图类型数,以便此View始终是正确的类型(请参阅getViewTypeCount()和getItemViewType(int))。

强调位说你不能依赖系统来传递一个正确类型的convertView,而最后一句则反过来说(就像我读的那样)。

基本上,我不知道为什么它不起作用。 我想在测试中你要检查自己是否必须给新视图充气

if(convertView == null)

你还应该检查它是否是正确的观点:

if(convertView == null || getItemViewTypeFromView(convertView) != type)

其中getItemViewTypeFromView()是这样的:

private int getItemViewTypeFromView(View view) {
    switch (view.getId()) {
        case R.id.item_layout_root:
            return TYPE_ITEM;
        case R.id.placeholder_layout_root:
            return TYPE_PLACEHOLDER;
        default: 
            throw new UnsupportedOperationException();
    }
}

在项目和占位符布局中,为根元素指定一个id,以便区分它们。 所以像这样:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/item_layout_root"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp" >

    ... snipped the elements that make up the body of the layout ...
</RelativeLayout>

我没有尝试过上述内容,所以我希望它适合你。

祝好运!

© www.soinside.com 2019 - 2024. All rights reserved.