如何在 RecyclerView 中获取 CardView 的宽度

How to get the width of CardView inside RecyclerView

这是我的 RecyclerView 的 xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/bikename_recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

这是由 RecyclerView 的适配器扩展的布局。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/bikenames_cardview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:orientation="vertical" >

            <ImageView
                android:id="@+id/bikenames_imageview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/bikenames_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
    </android.support.v7.widget.CardView>

 </LinearLayout>

所以这里我需要在我的 Activity 或 RecyclerView 适配器中找到 CardView (@id/bikenames_cardview) 的宽度。我也写过 RecyclerView 适配器。

适配器代码

public class BikeNamesAdapter extends RecyclerView.Adapter<BikeNamesViewHolder> {

    BikeNames bikeNames;
    Context context;

    public BikeNamesAdapter(BikeNames bikeNames) {
        this.bikeNames = bikeNames;
    }

    @Override
    public int getItemCount() {
        return bikeNames.getLength();
    }

    @Override
    public BikeNamesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        context = parent.getContext();
        View view = LayoutInflater.from(context).inflate(R.layout.cardview_bike_names, parent, false);
        return new BikeNamesViewHolder(view);
    }

    @Override
    public void onBindViewHolder(BikeNamesViewHolder holder, int position) {
         holder.textViewBikeName.setText(bikeNames.getBikeNameByIndex(position));

    }

}

我可能跳过了一些代码,以减少此处的长度。

onCreateViewHolder

中将侦听器设置为您的视图
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
  viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
      view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
      viewWidth = view.getWidth();
      viewHeight = view.getHeight();
    }
  });
}

同时检查这个和 this 问题。