当前位置: 移动技术网 > IT编程>移动开发>Android > Android自定义ViewGroup实现标签流容器FlowLayout

Android自定义ViewGroup实现标签流容器FlowLayout

2019年07月24日  | 移动技术网IT编程  | 我要评论

孽子风情,太原到北京的火车时刻表,霉女穿越记之乞丐王妃

本篇文章讲的是android 自定义viewgroup之实现标签流式布局-flowlayout,开发中我们会经常需要实现类似于热门标签等自动换行的流式布局的功能,网上也有很多这样的flowlayout,但不影响我对其的学习。和往常一样,主要还是想总结一下自定义viewgroup的开发过程以及一些需要注意的地方。

按照惯例,我们先来看看效果图


一、写代码之前,有几个是问题是我们先要弄清楚的:

1、什么是viewgroup:从名字上来看,它可以被翻译为控件组,言外之意是viewgroup内部包含了许多个控件,是一组view。在android的设计中,viewgroup也继承了view,这就意味着view本身就可以是单个控件也可以是由多个控件组成的一组控件;

2、viewgroup的种类:常见的有linearlayout、relativelayout、framelayout、absolutelayout、girdlayout、tablelayout。其中linearlayout和relativelayout使用的最多的两种;

3、viewgroup的职责:给childview计算出建议的宽和高和测量模式 ,然后决定childview的位置;

4、话说何为流式布局(flowlayout):就是控件根据viewgroup的宽,自动的从左往右添加。如果当前行还能放得这个子view,就放到当前行,如果当前行剩余的空间不足于容纳这个子view,则自动添加到下一行的最左边;

二、先总结下自定义viewgroup的步骤:

1、自定义viewgroup的属性
2、在viewgroup的构造方法中获得我们自定义的属性
3、重写onmesure
4、重写onlayout

三、viewgroup的几个构造函数:
1、public flowlayout(context context)
—>java代码直接new一个flowlayout实例的时候,会调用这个只有一个参数的构造函数;
2、public flowlayout(context context, attributeset attrs)
—>在默认的xml布局文件中创建的时候调用这个有两个参数的构造函数。attributeset类型的参数负责把xml布局文件中所自定义的属性通过attributeset带入到view内;
3、public flowlayout(context context, attributeset attrs, int defstyleattr)
—>构造函数中第三个参数是默认的style,这里的默认的style是指它在当前application或者activity所用的theme中的默认style,且只有在明确调用的时候才会调用
4、public flowlayout(context context, attributeset attrs, int defstyleattr, int defstyleres)
—>该构造函数是在api21的时候才添加上的

四、下面我们就开始来看看自定义viewgroup的主要代码啦

 1、自定义viewgroup的属性,首先在res/values/ 下建立一个attr.xml , 在里面定义我们的需要用到的属性以及声明相对应属性的取值类型

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <!--每个item纵向间距-->
 <attr name="verticalspacing" format="dimension" />
 <!-- 每个item横向间距-->
 <attr name="horizontalspacing" format="dimension" />

 <declare-styleable name="flowlayout">
 <attr name="verticalspacing" />
 <attr name="horizontalspacing" />
 </declare-styleable>

</resources>

我们定义了verticalspacing以及horizontalspacing2个属性,分别表示每个标签之间纵向间距和横向间距,其中format是值该属性的取值类型,format取值类型总共有10种,包括:string,color,demension,integer,enum,reference,float,boolean,fraction和flag。

2、然后在xml布局中声明我们的自定义view

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:custom="http://schemas.android.com/apk/res-auto"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

 <textview
 android:layout_width="match_parent"
 android:layout_height="48dp"
 android:background="#38353d"
 android:gravity="center"
 android:text="标签"
 android:textcolor="@android:color/white"
 android:textsize="16dp" />

 <scrollview
 android:layout_width="match_parent"
 android:layout_height="wrap_content">

 <linearlayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical">

 <textview
 android:id="@+id/tv_remind"
 android:layout_width="match_parent"
 android:layout_height="46dp"
 android:background="@android:color/white"
 android:gravity="center_vertical"
 android:paddingleft="15dp"
 android:text="我的标签(最多5个) "
 android:textsize="16dp" />

 <com.per.flowlayoutdome.flowlayout
 android:id="@+id/tcy_my_label"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@android:color/white"
 android:padding="5dp"
 android:visibility="gone"
 custom:horizontalspacing="6dp"
 custom:verticalspacing="12dp" />

 <view
 android:layout_width="match_parent"
 android:layout_height="10dp"
 android:background="#f6f6f6" />

 <relativelayout
 android:layout_width="match_parent"
 android:layout_height="46dp"
 android:background="@android:color/white">

 <textview
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_centervertical="true"
  android:paddingleft="15dp"
  android:text="推荐标签 "
  android:textsize="16dp" />
 </relativelayout>

 <view
 android:layout_width="match_parent"
 android:layout_height="1dp"
 android:background="#f6f6f6" />

 <com.per.flowlayoutdome.flowlayout
 android:id="@+id/tcy_hot_label"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@android:color/white"
 android:padding="5dp"
 custom:horizontalspacing="6dp"
 custom:verticalspacing="12dp" />
 </linearlayout>
 </scrollview>
</linearlayout>

一定要引入xmlns:custom=”http://schemas.android.com/apk/res-auto”,android studio中我们可以使用res-atuo命名空间,就不用在添加自定义view全类名。

3、在view的构造方法中,获得我们的自定义的样式

/**
 * 每个item纵向间距
 */
 private int mverticalspacing;
 /**
 * 每个item横向间距
 */
 private int mhorizontalspacing;

 public flowlayout(context context) {
 this(context, null);
 }

 public flowlayout(context context, attributeset attrs) {
 this(context, attrs, 0);
 }

 public flowlayout(context context, attributeset attrs, int defstyle) {
 super(context, attrs, defstyle);
 /**
 * 获得我们所定义的自定义样式属性
 */
 typedarray a = context.gettheme().obtainstyledattributes(attrs, r.styleable.flowlayout, defstyle, 0);
 for (int i = 0; i < a.getindexcount(); i++) {
 int attr = a.getindex(i);
 switch (attr) {
 case r.styleable.flowlayout_verticalspacing:
  mverticalspacing = a.getdimensionpixelsize(r.styleable.flowlayout_verticalspacing, 5);
  break;
 case r.styleable.flowlayout_horizontalspacing:
  mhorizontalspacing = a.getdimensionpixelsize(r.styleable.flowlayout_horizontalspacing, 10);
  break;
 }
 }
 a.recycle();
 }

我们重写了3个构造方法,在上面的构造方法中说过默认的布局文件调用的是两个参数的构造方法,所以记得让所有的构造方法调用三个参数的构造方法,然后在三个参数的构造方法中获得自定义属性。

一开始一个参数的构造方法和两个参数的构造方法是这样的:

 public flowlayout(context context) {
 super(context);
 }

 public flowlayout(context context, attributeset attrs) {
 super(context, attrs);
 }

有一点要注意的是super应该改成this,然后让一个参数的构造方法引用两个参数的构造方法,两个参数的构造方法引用三个参数的构造方法,代码如下:

 public flowlayout(context context) {
 this(context, null);
 }

 public flowlayout(context context, attributeset attrs) {
 this(context, attrs, 0);
 }

4、重写onmesure方法

/**
 * 负责设置子控件的测量模式和大小 根据所有子控件设置自己的宽和高
 */
 @override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
 /**
 * 获得此viewgroup上级容器为其推荐的宽和高,以及计算模式
 */
 int heighmode = measurespec.getmode(heightmeasurespec);
 int heighsize = measurespec.getsize(heightmeasurespec);
 int widthsize = measurespec.getsize(widthmeasurespec);
 /**
 * 高
 */
 int height = 0;
 /**
 * 每一行的高度,累加至height
 */
 int lineheight = 0;
 /**
 * 在warp_content情况下,记录当前childview的左边的一个位置
 */
 int childleft = getpaddingleft();
 /**
 * 在warp_content情况下,记录当前childview的上边的一个位置
 */
 int childtop = getpaddingtop();
 // getchildcount得到子view的数目,遍历循环出每个子view
 for (int i = 0; i < getchildcount(); i++) {
 //拿到index上的子view
 view childview = getchildat(i);
 // 测量每一个child的宽和高
 measurechild(childview, widthmeasurespec, heightmeasurespec);
 //当前子空间实际占据的高度
 int childheight = childview.getmeasuredheight();
 //当前子空间实际占据的宽度
 int childwidth = childview.getmeasuredwidth();
 lineheight = math.max(childheight, lineheight);// 取最大值
 //如果加入当前childview,超出最大宽度,则将目前最大宽度给width,类加height 然后开启新行
 if (childwidth + childleft + getpaddingright() > widthsize) {
 childleft = getpaddingleft();// 重新开启新行,开始记录childleft
 childtop += mverticalspacing + childheight;// 叠加当前的高度
 lineheight = childheight;// 开启记录下一行的高度
 }else{
 //否则累加当前childview的宽度
 childleft += childwidth + mhorizontalspacing;
 }
 }
 height += childtop + lineheight + getpaddingbottom();
 setmeasureddimension(widthsize, heighmode == measurespec.exactly ? heighsize : height);
 }

首先首先得到其父容器传入的测量模式和宽高的计算值,然后遍历所有的childview,使用measurechild方法对所有的childview进行测量。然后根据所有childview的测量得出的高得到该viewgroup如果设置为wrap_content时的高。最后根据模式,如果是measurespec.exactly则直接使用父viewgroup传入的高,否则设置为自己计算的高,细心的朋友会问,那儿宽呢,在这里我们默认宽为measurespec.exactly模式。

5、重写onlayout方法

@override
 protected void onlayout(boolean changed, int l, int t, int r, int b) {
 int width = r - l;
 int childleft = getpaddingleft();
 int childtop = getpaddingtop();
 int lineheight = 0;
 //遍历所有childview根据其宽和高,计算子控件应该出现的位置
 for (int i = 0; i < getchildcount(); i++) {
 final view childview = getchildat(i);
 if (childview.getvisibility() == view.gone) {
 continue;
 }
 int childwidth = childview.getmeasuredwidth();
 int childheight = childview.getmeasuredheight();
 lineheight = math.max(childheight, lineheight);
 // 如果已经需要换行
 if (childleft + childwidth + getpaddingright() > width) {
 childleft = getpaddingleft();
 childtop += mverticalspacing + lineheight;
 lineheight = childheight;
 }
 childview.layout(childleft, childtop, childleft + childwidth, childtop + childheight);
 childleft += childwidth + mhorizontalspacing;
 }
 }

onlayout中完成对所有childview的位置以及大小的指定

6、到此,我们对自定义viewgroup的代码已经写完了,有几点要注意的:
(1)getchildat(int index):获得index上的子view;
(2)getchildcount():得到所有子view的数目;
(3)measurechild(childview, widthmeasurespec, heightmeasurespec):使用子view自身的测量方法,测量每一个child的宽和高;

回归到主题,现在我们把自定义viewgroup,实现flowlayout的部分完成了,接下来的就是一些逻辑代码了

五、下面就是一些逻辑代码啦

1、我把flowlayout里面完整的代码贴出来:

package com.per.flowlayoutdome;

import android.content.context;
import android.content.res.typedarray;
import android.database.datasetobserver;
import android.util.attributeset;
import android.view.view;
import android.view.viewgroup;
import android.widget.baseadapter;

/**
 * @author: xiaolijuan
 * @description: 流式布局-标签流容器
 * @projectname: flowlayoutdome
 * @date: 2016-06-16
 * @time: 16:21
 */
public class flowlayout extends viewgroup{
 /**
 * 每个item纵向间距
 */
 private int mverticalspacing;
 /**
 * 每个item横向间距
 */
 private int mhorizontalspacing;
 private baseadapter madapter;
 private tagitemclicklistener mlistener;
 private datachangeobserver mobserver;

 public flowlayout(context context) {
 this(context, null);
 }

 public flowlayout(context context, attributeset attrs) {
 this(context, attrs, 0);
 }

 public flowlayout(context context, attributeset attrs, int defstyle) {
 super(context, attrs, defstyle);
 /**
 * 获得我们所定义的自定义样式属性
 */
 typedarray a = context.gettheme().obtainstyledattributes(attrs, r.styleable.flowlayout, defstyle, 0);
 for (int i = 0; i < a.getindexcount(); i++) {
 int attr = a.getindex(i);
 switch (attr) {
 case r.styleable.flowlayout_verticalspacing:
  mverticalspacing = a.getdimensionpixelsize(r.styleable.flowlayout_verticalspacing, 5);
  break;
 case r.styleable.flowlayout_horizontalspacing:
  mhorizontalspacing = a.getdimensionpixelsize(r.styleable.flowlayout_horizontalspacing, 10);
  break;
 }
 }
 a.recycle();
 }

 /**
 * 负责设置子控件的测量模式和大小 根据所有子控件设置自己的宽和高
 */
 @override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
 /**
 * 获得此viewgroup上级容器为其推荐的宽和高,以及计算模式
 */
 int heighmode = measurespec.getmode(heightmeasurespec);
 int heighsize = measurespec.getsize(heightmeasurespec);
 int widthsize = measurespec.getsize(widthmeasurespec);
 /**
 * 高
 */
 int height = 0;
 /**
 * 每一行的高度,累加至height
 */
 int lineheight = 0;
 /**
 * 在warp_content情况下,记录当前childview的左边的一个位置
 */
 int childleft = getpaddingleft();
 /**
 * 在warp_content情况下,记录当前childview的上边的一个位置
 */
 int childtop = getpaddingtop();
 // getchildcount得到子view的数目,遍历循环出每个子view
 for (int i = 0; i < getchildcount(); i++) {
 //拿到index上的子view
 view childview = getchildat(i);
 // 测量每一个child的宽和高
 measurechild(childview, widthmeasurespec, heightmeasurespec);
 //当前子空间实际占据的高度
 int childheight = childview.getmeasuredheight();
 //当前子空间实际占据的宽度
 int childwidth = childview.getmeasuredwidth();
 lineheight = math.max(childheight, lineheight);// 取最大值
 //如果加入当前childview,超出最大宽度,则将目前最大宽度给width,类加height 然后开启新行
 if (childwidth + childleft + getpaddingright() > widthsize) {
 childleft = getpaddingleft();// 重新开启新行,开始记录childleft
 childtop += mverticalspacing + childheight;// 叠加当前的高度
 lineheight = childheight;// 开启记录下一行的高度
 }else{
 //否则累加当前childview的宽度
 childleft += childwidth + mhorizontalspacing;
 }
 }
 height += childtop + lineheight + getpaddingbottom();
 setmeasureddimension(widthsize, heighmode == measurespec.exactly ? heighsize : height);
 }

 @override
 protected void onlayout(boolean changed, int l, int t, int r, int b) {
 int width = r - l;
 int childleft = getpaddingleft();
 int childtop = getpaddingtop();
 int lineheight = 0;
 //遍历所有childview根据其宽和高,计算子控件应该出现的位置
 for (int i = 0; i < getchildcount(); i++) {
 final view childview = getchildat(i);
 if (childview.getvisibility() == view.gone) {
 continue;
 }
 int childwidth = childview.getmeasuredwidth();
 int childheight = childview.getmeasuredheight();
 lineheight = math.max(childheight, lineheight);
 // 如果已经需要换行
 if (childleft + childwidth + getpaddingright() > width) {
 childleft = getpaddingleft();
 childtop += mverticalspacing + lineheight;
 lineheight = childheight;
 }
 childview.layout(childleft, childtop, childleft + childwidth, childtop + childheight);
 childleft += childwidth + mhorizontalspacing;
 }
 }

 private void drawlayout() {
 if (madapter == null || madapter.getcount() == 0) {
 return;
 }
 removeallviews();
 for (int i = 0; i < madapter.getcount(); i++) {
 view view = madapter.getview(i, null, null);
 final int position = i;
 view.setonclicklistener(new view.onclicklistener() {
 @override
 public void onclick(view v) {
  if (mlistener != null) {
  mlistener.itemclick(position);
  }
 }
 });
 addview(view);
 }
 }

 public void setadapter(baseadapter adapter) {
 if (madapter == null) {
 madapter = adapter;
 if (mobserver == null) {
 mobserver = new datachangeobserver();
 madapter.registerdatasetobserver(mobserver);
 }
 drawlayout();
 }
 }

 public void setitemclicklistener(tagitemclicklistener mlistener) {
 this.mlistener = mlistener;
 }

 public interface tagitemclicklistener {
 void itemclick(int position);
 }

 class datachangeobserver extends datasetobserver {
 @override
 public void onchanged() {
 drawlayout();
 }

 @override
 public void oninvalidated() {
 super.oninvalidated();
 }
 }
}

2、flowlayoutadapter

package com.per.flowlayoutdome;

import android.content.context;
import android.view.layoutinflater;
import android.view.view;
import android.view.viewgroup;
import android.widget.baseadapter;
import android.widget.button;

import java.util.list;

/**
 * @author: adan
 * @description: 流式布局适配器
 * @projectname: flowlayoutdome
 * @date: 2016-06-16
 * @time: 16:22
 */
public class flowlayoutadapter extends baseadapter {

 private context mcontext;
 private list<string> mlist;

 public flowlayoutadapter(context context, list<string> list) {
 mcontext = context;
 mlist = list;
 }

 @override
 public int getcount() {
 return mlist.size();
 }

 @override
 public string getitem(int position) {
 return mlist.get(position);
 }

 @override
 public long getitemid(int position) {
 return position;
 }

 @override
 public view getview(int position, view convertview, viewgroup parent) {
 viewholder holder;
 if (convertview == null) {
 convertview = layoutinflater.from(mcontext).inflate(
  r.layout.item_tag, null);
 holder = new viewholder();
 holder.mbtntag = (button) convertview.findviewbyid(r.id.btn_tag);
 convertview.settag(holder);
 } else {
 holder = (viewholder) convertview.gettag();
 }
 holder.mbtntag.settext(getitem(position));
 return convertview;
 }

 static class viewholder {
 button mbtntag;
 }
}

3、mainactivity

package com.per.flowlayoutdome;

import android.app.activity;
import android.content.intent;
import android.os.bundle;
import android.text.textutils;
import android.view.view;
import android.widget.textview;
import android.widget.toast;

import java.util.arraylist;
import java.util.list;


public class mainactivity extends activity {
 private textview tv_remind;

 private flowlayout tcy_my_label, tcy_hot_label;
 private flowlayoutadapter mmylabeladapter, mhotlabeladapter;
 private list<string> mylabellists, hotlabellists;

 private static int tag_requestcode = 0x101;

 @override
 protected void oncreate(bundle savedinstancestate) {
 super.oncreate(savedinstancestate);
 setcontentview(r.layout.activity_main);
 initview();
 initdata();
 }

 private void initview() {
 tv_remind = (textview) findviewbyid(r.id.tv_remind);
 tcy_my_label = (flowlayout) findviewbyid(r.id.tcy_my_label);
 tcy_hot_label = (flowlayout) findviewbyid(r.id.tcy_hot_label);
 }

 private void initdata() {
 string[] date = getresources().getstringarray(r.array.tags);
 hotlabellists = new arraylist<>();
 for (int i = 0; i < date.length; i++) {
 hotlabellists.add(date[i]);
 }
 mhotlabeladapter = new flowlayoutadapter(this, hotlabellists);
 tcy_hot_label.setadapter(mhotlabeladapter);
 tcy_hot_label.setitemclicklistener(new tagcloudlayoutitemonclick(1));

 mylabellists = new arraylist<>();
 mmylabeladapter = new flowlayoutadapter(this, mylabellists);
 tcy_my_label.setadapter(mmylabeladapter);
 tcy_my_label.setitemclicklistener(new tagcloudlayoutitemonclick(0));

 string labels = string.valueof(getintent().getstringextra("labels"));
 if (!textutils.isempty(labels) && labels.length() > 0
 && !labels.equals("null")) {
 string[] temp = labels.split(",");
 for (int i = 0; i < temp.length; i++) {
 mylabellists.add(temp[i]);
 }
 changemylabels();
 }

 }

 /**
 * 刷新我的标签数据
 */
 private void changemylabels() {
 tv_remind.setvisibility(mylabellists.size() > 0 ? view.gone
 : view.visible);
 tcy_my_label.setvisibility(mylabellists.size() > 0 ? view.visible
 : view.gone);
 mmylabeladapter.notifydatasetchanged();
 }

 /**
 * 标签的点击事件
 *
 * @author lijuan
 */
 class tagcloudlayoutitemonclick implements flowlayout.tagitemclicklistener {
 int index;

 public tagcloudlayoutitemonclick(int index) {
 this.index = index;
 }

 @override
 public void itemclick(int position) {
 switch (index) {
 case 0:
  mylabellists.remove(mylabellists.get(position));
  changemylabels();
  break;
 case 1:
  if (mylabellists.size() < 5) {
  if (hotlabellists.get(position).equals("自定义")) {
  startactivityforresult(
   new intent(mainactivity.this,
   addtagactivity.class),
   tag_requestcode);
  } else {
  boolean isexits = isexist(mylabellists,
   hotlabellists.get(position));
  if (isexits) {
  toast.maketext(mainactivity.this, "此标签已经添加啦", toast.length_long).show();
  return;
  }
  mylabellists.add(hotlabellists.get(position));
  changemylabels();
  }
  } else {
  toast.maketext(mainactivity.this, "最多只能添加5个标签", toast.length_long).show();
  }
  break;
 default:
  break;
 }
 }
 }

 /**
 * 将数组里面的字符串遍历一遍,看是否存在相同标签
 *
 * @param str
 * @param comparestr
 * @return
 */
 public static boolean isexist(list<string> str, string comparestr) {
 boolean isexist = false;//默认沒有相同标签
 for (int i = 0; i < str.size(); i++) {
 if (comparestr.equals(str.get(i))) {
 isexist = true;
 }
 }
 return isexist;
 }

 /**
 * 回传数据
 */
 @override
 protected void onactivityresult(int requestcode, int resultcode, intent data) {
 if (tag_requestcode == requestcode) {
 if (resultcode == addtagactivity.tag_resultcode) {
 string label = data.getstringextra("tags");
 mylabellists.add(label);
 changemylabels();
 }
 }
 }
}

4、addtagactivity

package com.per.flowlayoutdome;

import android.app.activity;
import android.content.intent;
import android.os.bundle;
import android.text.editable;
import android.text.textutils;
import android.text.textwatcher;
import android.view.view;
import android.widget.button;
import android.widget.edittext;
import android.widget.toast;

/**
 * @author: xiaolijuan
 * @description: 添加自定义标签
 * @date: 2016-06-10
 * @time: 14:37
 */
public class addtagactivity extends activity implements view.onclicklistener{

 private edittext metlabel;
 private button mbtnsure;
 public final static int tag_resultcode = 0x102;

 @override
 protected void oncreate(bundle savedinstancestate) {
 super.oncreate(savedinstancestate);
 setcontentview(r.layout.activity_add_tag);
 initview();
 initdata();
 }

 private void initdata() {
 // 根据输入框输入值的改变提示最大允许输入的个数
 metlabel.addtextchangedlistener(new textwatcher_enum());
 }

 private void initview() {
 metlabel = (edittext) findviewbyid(r.id.et_label);
 mbtnsure = (button) findviewbyid(r.id.btn_sure);

 mbtnsure.setonclicklistener(this);
 }

 @override
 public void onclick(view v) {
 switch (v.getid()) {
 case r.id.btn_sure:
 string label = metlabel.gettext().tostring();
 if (textutils.isempty(label)) {
  toast.maketext(addtagactivity.this,"自定义标签不应为空",toast.length_long).show();
  return;
 }
 intent intent = getintent();
 intent.putextra("tags", label);
 setresult(tag_resultcode, intent);
 finish();
 break;
 }
 }

 /**
 * 根据输入框输入值的长度超过8个字符的时候,弹出输入的标签应控制在8个字
 *
 * @author lijuan
 *
 */
 class textwatcher_enum implements textwatcher {
 @override
 public void beforetextchanged(charsequence s, int start, int count,
   int after) {
 }

 @override
 public void ontextchanged(charsequence s, int start, int before,
   int count) {
 int lenght = metlabel.gettext().tostring().trim().length();
 if (lenght > 8) {
 toast.maketext(addtagactivity.this,"输入的标签应控制在8个字",toast.length_long).show();
 }
 }

 @override
 public void aftertextchanged(editable s) {

 }
 }
}

5、activity_main.xml在上面已经贴出来了,在这里就不重复了,我们创建了arrays.xml,在这里定义了一写热门的标签:

<?xml version="1.0" encoding="utf-8"?>
<resources>

 <string-array name="tags">
 <item>美妆</item>
 <item>画板</item>
 <item>漫画</item>
 <item>高科技</item>
 <item>韩国电影</item>
 <item>股票</item>
 <item>美术</item>
 <item>高富帅</item>
 <item>鸿泰安</item>
 <item>运动</item>
 <item>外语</item>
 <item>财经</item>
 <item>大叔</item>
 <item>非主流</item>
 <item>暴走漫画</item>
 <item>心理学</item>
 <item>汉语</item>
 <item>白富美</item>
 <item>自定义</item>
 </string-array>

</resources>

6、item_tag.xml

<?xml version="1.0" encoding="utf-8"?>
<button xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/btn_tag"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:background="@drawable/selector_btn_item"
 android:gravity="center"
 android:minheight="30dp"
 android:minwidth="45dp"
 android:paddingleft="16dp"
 android:paddingright="16dp"
 android:textsize="12sp" />

6、activity_add_tag.xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="250dp"
 android:layout_height="wrap_content"
 android:background="@android:color/white"
 android:gravity="center_horizontal"
 android:orientation="vertical"
 android:padding="5dp" >

 <linearlayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical" >

 <textview
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginleft="5dp"
 android:text="请输入想要添加的标签"
 android:textcolor="@android:color/black"
 android:textsize="16dp" />

 <edittext
 android:id="@+id/et_label"
 android:layout_width="match_parent"
 android:layout_height="80dp"
 android:layout_margin="5dp"
 android:background="@drawable/selector_btn_item"
 android:gravity="center_vertical|start"
 android:maxlength="8"
 android:paddingleft="10dp"
 android:textcolor="@android:color/black"
 android:textsize="16dp" />
 </linearlayout>

 <button
 android:id="@+id/btn_sure"
 android:layout_width="50dp"
 android:layout_height="32dp"
 android:layout_marginleft="16dp"
 android:layout_marginright="16dp"
 android:layout_margintop="5dp"
 android:background="#38353d"
 android:gravity="center"
 android:text="确定"
 android:textcolor="@android:color/white"
 android:textsize="14dp" />

</linearlayout>

7、selector_btn_item.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_pressed="true">
 <shape>
 <solid android:color="#ff76787b" />
 <corners android:bottomleftradius="5dp" android:bottomrightradius="5dp" android:topleftradius="5dp" android:toprightradius="5dp" />
 <stroke android:width="1px" android:color="#ffd1d1d1" />
 </shape>
 </item>
 <item>
 <shape>
 <solid android:color="#ffffff" />
 <corners android:bottomleftradius="2.5dp" android:bottomrightradius="2.5dp" android:topleftradius="2.5dp" android:toprightradius="2.5dp" />
 <stroke android:width="0.5px" android:color="#ffd1d1d1" />
 </shape>
 </item>
</selector>

最后一点了吧,我们在androidmanifest.xml中需要添加

<activity
 android:name=".addtagactivity"
 android:theme="@style/dialogstyle" />

用于我们自定义标签,弹出的一个类似于对话框的一个activity,这里我们引用了自定义一个样式

<style name="dialogstyle">
 <!--设置dialog的背景-->
 <item name="android:windowbackground">@android:color/transparent</item>
 <!--设置dialog的windowframe框为无-->
 <item name="android:windowframe">@null</item>
 <!--设置无标题-->
 <item name="android:windownotitle">true</item>
 <!--是否浮现在activity之上-->
 <item name="android:windowisfloating">true</item>
 <!--是否半透明-->
 <item name="android:windowistranslucent">true</item>
 <!--设置窗口内容不覆盖-->
 <item name="android:windowcontentoverlay">@null</item>
 <!--设置动画,在这里使用让它继承系统的animation.dialog-->
 <item name="android:windowanimationstyle">@android:style/animation.dialog</item>
 <!--背景是否模糊显示-->
 <item name="android:backgrounddimenabled">true</item>
 </style>

对于这个类似于对话框的一个activity,有不明白的可以上我之前的一篇文章: android中使用dialog风格弹出框的activity

源码下载:

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网