自我接觸FlexboxLayout以來,基本看過的每一篇博客都會提及FlexboxLayout與Recyclerview結合使用,Google的例子裏實現的效果類似於瀑布流。
雖然到現在我也沒有在實際的項目中應用過這個組合,但我寫了個小demo來實現這個組合的簡單應用。
FlexboxLayout與Recycleview結合使用首先要引用'com.google.android:flexbox:0.3.0-alpha2',android studio的朋友也可以直接下載這個包(http://download.csdn.net/detail/qq_35366908/9796053),然後添加
Model依賴就可以正常使用使用了
用過Recyclerview的都知道,Recyclerview要添加一個佈局管理器,之前都是添加一個LinearLayoutManager,代碼如下:
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));//這個佈局管理器可以設置Recycleview的顯示形式(默認是Vertical顯示),是否滾動,設置分割線屬性等等。
/**LayoutManager for the {@link RecyclerView}. This class is intended to be used within a
* {@link RecyclerView} and offers the same capabilities of measure/layout its children
* as the {@link FlexboxLayout}. */
大概就是爲RecyclerView提供相同功能的FlexBoxLayout佈局
private void initRecycleView() {
mRecyclerView = (RecyclerView) findViewById(R.id.rv_combine_fiexBox);
FlexboxLayoutManager manager = new FlexboxLayoutManager();
//設置主軸排列方式
manager.setFlexDirection(FlexDirection.ROW);
//設置是否換行
manager.setFlexWrap(FlexWrap.WRAP);
manager.setAlignItems(AlignItems.STRETCH);
mRecyclerView.setLayoutManager(manager);
mAdpter = new RvFlexAdapter(mDates, this);
mRecyclerView.setAdapter(mAdpter);
}
在RecyclerView 的adapter中,獲取item控件,對控件的佈局參數可以進行設置(屬性可參考FlexboxLayout的子控件屬性)我只帶佈局中添加了一個ImageView在ViewHolder中提供了獲取ImageView的get方法。
@Override
public void onBindViewHolder(BaseFvFlexViewHolder holder, int position) {
ImageView mImageView = holder.getImageView(R.id.tv_title);
holder.tvTitle.setImageResource(mTitles[position]);
// holder.tvTitle.setText(mTitles[position]+"");
ViewGroup.LayoutParams lp = mImageView.getLayoutParams();
if (lp instanceof FlexboxLayoutManager.LayoutParams) {
FlexboxLayoutManager.LayoutParams flexboxLp =
(FlexboxLayoutManager.LayoutParams) mImageView.getLayoutParams();
flexboxLp.setFlexGrow(1);
}
}
就簡單的實現了FlexboxLayout與RecyclerView的結合使用,對於Item的佈局,最外層佈局不要填充父控件要wrap_content ,若是給match_parent就會一行只顯示一個圖片,看不出換行的效果,我的測試item佈局如下:子控件的尺寸可以根據需求來定義。
<?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:orientation="vertical">
<ImageView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="70dp"
android:layout_margin="5dp"
android:visibility="visible" />
<!--<TextView-->
<!--android:id="@+id/tv_title"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_margin="5dp"-->
<!--android:gravity="center_vertical"-->
<!--android:textSize="16sp"-->
<!--android:visibility="visible" />-->
</LinearLayout>
因爲圖片資源有限,我也換過用TextView來測試,效果可能比我找的圖片好一些。