? ? ? ? RecycleView目前已經(jīng)取代ListView、GridView成為主流滑動列表首選組件巷查,在各類列表展示中都能一展風(fēng)采,下面主要講講如何設(shè)置它的item固定寬高比及適配不同的機(jī)型展現(xiàn)統(tǒng)一的樣式藕坯。
? ? ? 控制寬高比首選約束布局界睁,它的實(shí)現(xiàn)方式最為簡潔,重點(diǎn)是設(shè)置約束比例:layout_constraintDimensionRatio(注:約束比例要生效彻亲,layout_width或者layout_height至少有一個的值需要為0dp孕锄,否則約束比例不生效),直接來看看item布局的實(shí)現(xiàn)方式吧:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
? ? xmlns:app="http://schemas.android.com/apk/res-auto"
? ? android:layout_width="match_parent"
? ? android:layout_height="wrap_content">
<ImageView
? ? ? ? android:id="@+id/image"
? ? ? ? android:layout_width="0dp"
? ? ? ? android:layout_height="0dp"
? ? ? ? android:scaleType="centerCrop"
? ? ? ? android:src="@drawable/img"
? ? ? ? app:layout_constraintDimensionRatio="h,16:9"
? ? ? ? app:layout_constraintLeft_toLeftOf="parent"
? ? ? ? app:layout_constraintRight_toRightOf="parent"
? ? ? ? app:layout_constraintTop_toTopOf="parent"
? ? ? ? app:layout_constraintBottom_toBottomOf="parent"
? ? ? ? />
</android.support.constraint.ConstraintLayout>
此時苞尝,item是鋪滿整個布局畸肆,只是根據(jù)圖片的寬度保持了寬高比,當(dāng)設(shè)置RecycleView水平滾動時宙址,圖片寬度會占滿一個屏幕轴脐,需要設(shè)置item的寬度。如果設(shè)置固定值抡砂,則在不同手機(jī)上同一屏展示的item數(shù)量可能會不同大咱,此時在adapter初始化實(shí)例的時候,onCreateViewHolder方法中強(qiáng)行設(shè)置item的寬度注益,比如設(shè)置為屏幕寬度的40%碴巾,具體實(shí)現(xiàn)如下:
//加載item 的布局 創(chuàng)建ViewHolder實(shí)例
@Override
public ViewHolderonCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_horizontal_img, parent,false);
? ? ConstraintLayout.LayoutParams param =new ConstraintLayout.LayoutParams(view.getLayoutParams());
? ? WindowManager wm = (WindowManager) parent.getContext().getSystemService(parent.getContext().WINDOW_SERVICE);
? ? DisplayMetrics dm =new DisplayMetrics();
? ? wm.getDefaultDisplay().getMetrics(dm);
? ? int width = dm.widthPixels;? ? ? ? // 屏幕寬度(像素)
? ? param.width = (int)(width*0.4);
? ? view.setLayoutParams(param);
? ? ViewHolder holder =new ViewHolder(view);
? ? return holder;
}
設(shè)置完成以后item所占寬度為屏幕的40%,因?yàn)閷挾仁歉鶕?jù)屏幕獲取丑搔,故在所有手機(jī)上占用寬度都一樣厦瓢,最終實(shí)現(xiàn)效果如下圖: