效果圖:熱門專題下方就是一個Flexbox的效果,截圖來自簡書
使用:
1.添加依賴
compile 'com.google.android:flexbox:0.2.2'
2.佈局文件簡例
<com.google.android.flexbox.FlexboxLayout
android:id="@+id/flexbox_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flexWrap="wrap" />
其中flexWrap 這個屬性決定Flex 容器是單行還是多行,並且決定副軸(與主軸垂直的軸)的方向。可能有以下3個值:
- noWrap: 不換行,一行顯示完子元素。
- wrap: 按正常方向換行。
- wrap_reverse: 按反方向換行
String[] tags = {"婚姻育兒", "散文", "設計", "上班這點事兒", "影視天堂", "大學生活", "美人說", "運動和健身", "工具癖", "生活家", "程序員", "想法", "短篇小說", "美食", "教育", "心理", "奇思妙想", "美食", "攝影"};
flexboxLayout = (FlexboxLayout) findViewById(R.id.flexbox_layout);
for (int i = 0; i < tags.length; i++) {
DataBean model = new DataBean();
model.setId(i);
model.setTitle(tags[i]);
flexboxLayout.addView(createNewFlexItemTextView(model));
}
/**
* 動態創建TextView
* @param book
* @return
*/
private TextView createNewFlexItemTextView(final DataBean book) {
TextView textView = new TextView(this);
textView.setGravity(Gravity.CENTER);
textView.setText(book.getTitle());
textView.setTextSize(12);
textView.setTextColor(getResources().getColor(R.color.colorAccent));
// textView.setBackgroundResource(R.drawable.tag_states);
textView.setTag(book.getId());
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.e("TAG", book.getTitle());
}
});
int padding = Utils.dp2px(this, 4);//隨意搜到的dp轉px的一個方法
int paddingLeftAndRight = Utils.dp2px(this, 8);
ViewCompat.setPaddingRelative(textView, paddingLeftAndRight, padding, paddingLeftAndRight, padding);
FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
int margin = Utils.dp2px(this, 6);
int marginTop = Utils.dp2px(this, 16);
layoutParams.setMargins(margin, marginTop, margin, 0);
textView.setLayoutParams(layoutParams);
return textView;
}