所以这是我的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));
}
}
我可能跳过了一些代码,以减少这里的长度。
答案 0 :(得分:7)
将监听器设置为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问题。