FlexboxLayout淺析

效果圖:熱門專題下方就是一個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: 按反方向換行
3.向其中填充數據的簡介
我們此處要做的是將一堆詞變成像上圖一樣的專題Flexbox樣式
        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;
    }


做法是,將詞組扔進數組後,綁定控件,抽象出一個Bean類來存放數據,通過addView,來循環放入子View

子View的樣式,點擊事件,間距控制,都通過createNewFlexItemTextView當中定義。

發佈了35 篇原創文章 · 獲贊 11 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章