1. 程式人生 > >android商品屬性選擇標籤控制元件,可實現自動換行

android商品屬性選擇標籤控制元件,可實現自動換行

一、demo功能

在電商專案中,商品屬性選擇是必不可少的,而且屬性的數目和長度不是固定的,就有了 “標籤選擇”。以下我就借用了開源的AutoFlowLayout控制元件,根據商品屬性選擇要求寫了這個demo,和大家分享

二、程式碼介紹

1.功能

AutoFlowLayout具有很多功能,比如自動換行,支援單選/多選,支援行居中/靠左顯示,支援單行/多行顯示,支援子View點選/長按事件,支援新增/刪除子View,等等,如果感興趣,自己可以去研究下,
下面附下AutoFlowLayout開源專案demo的地址:
http://www.jcodecraeer.com/a/opensource/2017/0806/8346.html


此demo功能比較齊全,因我的專案裡一些功能不需要,所以我就把商品屬相所需要的標籤單選,預設選中第一個標籤,選擇顏色改變功能進行摘取,完善;
寫了此demo,程式碼簡單,不需要依賴,方便用在專案中,希望對大家有用;

2.使用

佈局檔案:
    <com.ss.goodsattributeselect.AutoFlowLayout
        android:id="@+id/afl_cotent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
 主activity
 //動態新增每個Tag
 for (int i = 0; i< mData.length; i ++ ){
     View item = LayoutInflater.from(this).inflate(R.layout.attribute_item, null);
     TextView tvAttrTag = (TextView) item.findViewById(R.id.tv_attr_tag);
     tvAttrTag.setText(mData[i]);
     mFlowLayout.addView(item);
 }
 
//預設第一個為選中狀態
mFlowLayout.getChildAt(0).setSelected(true);
attribute = mData[0];

//item點選事件
 mFlowLayout.setOnItemClickListener(new AutoFlowLayout.OnItemClickListener() {
 @Override
 public void onItemClick(int position, View view) {
	  //當選中別的item時,將預設第一個選中去掉
	  if (position != 0){  
           mFlowLayout.getChildAt(0).setSelected(false);
       }
      //當連續點選相同的item時,防止取消選中
     if (attribute.equals(mData[position])){              
     mFlowLayout.getChildAt(position).setSelected(true);
     }
     attribute = mData[position];
     }
 });

3.效果圖

預設選中第一個
這裡寫圖片描述

可自由選擇商品屬性
這裡寫圖片描述