【Android界⾯效果49】RecyclerView⾼度随Item⾃适应
编写RecyclerView.ItemDecoration时,在onDraw⽅法中,Drawable的⾼度等于RecyclerView的⾼度减去RecyclerView的上下padding。
@Override
public void onDraw(Canvas c, RecyclerView parent, State state) {
int top = PaddingTop();
int bottom = Height() - PaddingBottom();
int childCount = ChildCount();
for(int i=0;i < childCount;i++){
View child = ChildAt(i);
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams();
int left = Right() + layoutParams.rightMargin;
int right = left + IntrinsicWidth();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
但运⾏后的显⽰效果却和我的预期相差很⼤
可以看到,ItemDecoration⾼度竟然全屏了,然后检查xml布局⽂件:
l
<RelativeLayout xmlns:android="schemas.android/apk/res/android"
xmlns:tools="schemas.android/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="lerviewdemo.MainActivity" >
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="schemas.android/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⾼度相关说明,看来只能⾃⼰动⼿丰⾐⾜⾷了。
根据⾥提到的,RecyclerView并不负责Item的显⽰⼯作,⽽Adapter负责的是数据仓库和Item的视图,所以最终把⽬标锁定到 RecyclerView.LayoutManager上。于是尝试继承LinearLayoutManager,发现果然有onMeasure⽅法:android layout布局
public void onMeasure(Recycler recycler, State state, int widthSpec,int heightSpec)
在onMeasure中可以获得RecyclerView.Recycler。Recycler负责管理Item视图的重复利⽤,所以我们可以通过Recycler获取⼀个Item视图的实例,然后像复写其他ViewGroup⼀样,使⽤measureChild获取⼦视图的⾼度后使⽤setMeasuredDimension设置 RecyclerView同样的⾼度即可。
public class MyLayoutManager extends LinearLayoutManager {
public MyLayoutManager(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
public void onMeasure(Recycler recycler, State state, int widthSpec,int heightSpec) {
View view = ViewForPosition(0);
if(view != null){
measureChild(view, widthSpec, heightSpec);
int measuredWidth = Size(widthSpec);
int measuredHeight = MeasuredHeight();
setMeasuredDimension(measuredWidth, measuredHeight);
}
}
}
修改完之后的运⾏效果图:
最后奉上⽰例程序。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。