昨天UI妹子給了給需求牛郑,展示水平分頁效果,而且第二頁要默認(rèn)顯示一部分敬鬓,提示用戶水平可以滑動(dòng)淹朋,先上效果圖:
GIF.gif
笙各,很明顯橫向滑動(dòng)的分頁,第一反應(yīng)就是使用ViewPager础芍,畢竟只要通過自定義ViewPager杈抢,實(shí)現(xiàn)這個(gè)效果還是很容易,但是實(shí)際中問題時(shí)仑性,當(dāng)前模塊是Recyclerview中某一個(gè)Holder惶楼,為了性能,肯定盡量使用Recyclerview去復(fù)用View诊杆,而且ViewPager并不能復(fù)用歼捐,所以考慮之后,還是要用Recyclerview去實(shí)現(xiàn)刽辙。
解決思路
既然打算用Recyclerview實(shí)現(xiàn)窥岩,很明顯這就可以用GridLayoutManager處理橫向滑動(dòng)的列表甲献,初步實(shí)現(xiàn)橫向列表的效果宰缤,列數(shù)為4的橫向分頁效果
GIF.gif
橫向列表效果是實(shí)現(xiàn)了,但是并沒有達(dá)到設(shè)計(jì)稿的要求晃洒,第二頁要默認(rèn)顯示一部分慨灭,那么就要從水平方向上去思考解決問題,既然第二頁要顯示一部分球及,假如顯示16dp氧骤,那么將第一頁列表寬度減少右邊距16dp,第二頁就可以在第一頁顯示了吃引。
在Recyclerview的Adapter中筹陵,先上布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl_parent"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="@drawable/news_click_bg"
android:clickable="true"
android:gravity="center_vertical">
<ImageView
android:id="@+id/iv_img"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_centerVertical="true"
android:layout_marginLeft="16dp"
android:padding="3dp"
android:src="@drawable/icon_book_default"
android:tint="@color/blue" />
<com.ddz.lifestyle.baseview.customview.RobotoTextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:layout_marginRight="20dp"
android:layout_toRightOf="@+id/iv_img"
android:ellipsize="end"
android:lines="1"
android:textSize="18sp"
app:typeface="roboto_regular"
tools:text="name" />
<ImageView
android:id="@+id/iv_menu"
android:layout_width="34dp"
android:layout_height="34dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:padding="10dp"
android:src="@drawable/menu_right"
android:visibility="invisible" />
</RelativeLayout>```
在onBindViewHolder方法中,去修改邊距
@Override
public void onBindViewHolder(ItemHolder holder, int position) {
if (null == bean) {
return;
}
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DensityUtil.dip2px(86)); //DensityUtil是px轉(zhuǎn)dp的工具類
int screenWidth = TCommonUtils.getScreenWidth(context);
if (position <= 3) { //因?yàn)槊苛袛?shù)量為4個(gè)镊尺,那么只需要將前4個(gè)item的寬度減少32dp
screenWidth -= DensityUtil.dip2px(32); //寬度減少32dp,即左右各16dp
params.width = screenWidth;
} else {
params.width = screenWidth;
}
holder.rlParent.setLayoutParams(params);
holder.tvTitle.setText(bean.get(position).getTitle());
}```
來看看效果
GIF.gif
可以看到默認(rèn)第二頁可以顯示一部分朦佩,而且后面每一頁都正常顯示,沒有像第二頁一樣侵入上一頁中
總結(jié)
實(shí)現(xiàn)這種分頁效果的方法有很多庐氮,但是選擇最容易并且效率最高的方式语稠,才是開發(fā)中需要的。