Android自定义控件实现标签的显示自动换行(一)

时间:2021-10-12 06:02:24

通过控件TagListView实现父控件,然后向里面添加子空间TagView


代码如下:

布局文件:

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

<TextView
android:id="@+id/tag_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="@dimen/common_margin"
android:paddingRight="@dimen/common_margin"
android:paddingTop="16.0dip"
android:text="标签 (选择1-6项)"
android:textColor="@color/color_shenhui"
android:textSize="16.0sp" />

<com.niceapp.lib.tagview.widget.TagListView
xmlns:f="http://schemas.android.com/apk/res-auto"
android:id="@+id/tagview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/common_margin"
android:paddingLeft="@dimen/common_margin"
android:paddingRight="@dimen/common_margin"
android:paddingTop="16.0dip"
f:horizontalSpacing="@dimen/tag_horizontal_spacing"
f:orientation="horizontal"
f:verticalSpacing="@dimen/tag_vertical_spacing" />

</LinearLayout>

实现代码:

import android.app.Activity;
import android.os.Bundle;
import com.niceapp.lib.tagview.widget.Tag;
import com.niceapp.lib.tagview.widget.TagListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {

private TagListView mTagListView;
private final List<Tag> mTags = new ArrayList<Tag>();
<span style="white-space:pre"></span>private final String[] titles = { "安全必备", "音乐", "父母学", "上班族必备",
<span style="white-space:pre"></span>"360手机卫士", "QQ","输入法", "微信", "最美应用", "AndevUI", "蘑菇街" };@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.select_tag_activity);mTagListView = (TagListView) findViewById(R.id.tagview);setUpData();mTagListView.setTags(mTags);}private void setUpData() {for (int i = 0; i < 10; i++) {Tag tag = new Tag();tag.setId(i);tag.setChecked(true);tag.setTitle(titles[i]);mTags.add(tag);}}}


运行结果如下:

Android自定义控件实现标签的显示自动换行(一)

具体的控件的代码,请下载源码