编写RecyclerView.ItemDecoration时,在onDraw方法中,Drawable的高度等于RecyclerView的高度减去RecyclerView的上下padding。
@Override public void onDraw(Canvas c, RecyclerView parent, State state) { int top = parent.getPaddingTop(); int bottom = parent.getHeight() - parent.getPaddingBottom(); int childCount = parent.getChildCount(); for(int i=0;i < childCount;i++){ View child = parent.getChildAt(i); RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams)child.getLayoutParams(); int left = child.getRight() + layoutParams.rightMargin; int right = left + mDivider.getIntrinsicWidth(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } }
但运行后的显示效果却和我的预期相差很大
可以看到,ItemDecoration高度竟然全屏了,然后检查xml布局文件:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.xmy.recylerviewdemo.MainActivity" > <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RelativeLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:padding="10.0dip" android:orientation="vertical" > <ImageView android:id="@+id/item_iv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleType="center" android:src="@drawable/img" android:adjustViewBounds="true"/> <TextView android:id="@+id/item_tv" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
xml布局文件中RecyclerView和Item的高度都设定的是wrap_content,那说好的自适应于item高度呢?查看Android文档,没发现有关RecyclerView高度相关说明,看来只能自己动手丰衣足食了。
根据Android-RecylerView初识里 提到的,RecyclerView并不负责Item的显示工作,而Adapter负责的是数据仓库和Item的视图,所以最终把目标锁定到 RecyclerView.LayoutManager上。于是尝试继承LinearLayoutManager,发现果然有onMeasure方法:
public void onMeasure(Recycler recycler, State state, int widthSpec,int heightSpec)
来源:https://www.cnblogs.com/dongdong230/p/4315630.html