欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android流式布局FlowLayout详解

程序员文章站 2022-07-01 16:19:23
现在商城类的app几乎都要用到流式布局来实现选择属性功能,在我的demo中是通过flowlayout工具类实现流式布局 使用起来非常简单,十几行代码就可以实现; 在...

现在商城类的app几乎都要用到流式布局来实现选择属性功能,在我的demo中是通过flowlayout工具类实现流式布局
使用起来非常简单,十几行代码就可以实现;

Android流式布局FlowLayout详解

在我们的项目中大部分都是单选效果,为了防止用到多选,demo中也实现了多选;

flowlayout大家不用研究怎么实现的,只要会使用就好;

就好比谷歌提供的listview条目点击事件一样,只要会用就好,没必要研究个所以然;大家在用的时候直接从demo中复制到项目中即可;

大家可以将flowlayout理解为一个线性布局;将准备好的一个个子view添加到flowlayout中即可;

首先看下布局文件:

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  xmlns:app="http://schemas.android.com/apk/res-auto"> 
 
  <!-- 
  app:horizontal_spacing="8dp" 每列之间的距离 
  app:vertical_spacing="8dp"  每行之间的距离 
  --> 
  <www.fl.com.flowlayouttext.view.flowlayout 
    android:id="@+id/flowlayout" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_margintop="20dp" 
    android:paddingbottom="14dp" 
    android:paddingleft="21dp" 
    android:paddingright="14dp" 
    app:horizontal_spacing="8dp" 
    app:vertical_spacing="8dp"/> 
   
</linearlayout> 

布局文件非常简单,没什么好说的,下面看下代码实现:
大致分为三步:

//第一步:初始化flowlayout 
     flowlayout= (flowlayout) findviewbyid(r.id.flowlayout); 
    //第二步:移除flowlayout中的所有子布局 
     flowlayout.removeallviews(); 
    //第三步:循环创建子view,添加到flowlayout中 
     for (int x=0;x<names.length;x++){ 
      //3.1初始化子view 
      checkbox checkbox= (checkbox) view.inflate(context,r.layout.item_flowlayout,null); 
      checkbox.settext(names[x]); 
 
      final int finalx = x; 
      //3.2设置子view的点击事件 
      checkbox.setonclicklistener(new view.onclicklistener() { 
        @override 
        public void onclick(view v) { 
          toastutil.show(context, names[finalx]); 
          //遍历flowlayout中的所有view,如果是当前选中的view,设置为选中状态,其他设置为未选中状态 
          refreshcheckbox(names[finalx]); 
        } 
      }); 
      //3.3将子view添加到flowlayout中 
      flowlayout.addview(checkbox); 
    } 

从代码中可以看到,子view使用的是checkbox,背景和文字颜色都是使用的状态选择器,大家可以根据自己项目中的需求随意更改:

item_flowlayout.xml

<?xml version="1.0" encoding="utf-8"?> 
<checkbox xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
  android:button="@null" 
  android:textsize="15sp" 
  android:paddingleft="5dp" 
  android:paddingright="5dp" 
  android:background="@drawable/item_bg_select" 
  android:textcolor="@drawable/text_color" 
  android:paddingtop="3dp" 
  android:paddingbottom="3dp"> 
</checkbox> 

单选到此结束,大家可能感觉多选比单选要难,其实多选比单选还要简单,以上代码只需去除子view点击事件refreshcheckbox()方法即可实现多选;

点击打开链接免费下载源码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。