在做Android开发的时候,会遇到动态添加标签让用户选择的功能,所以自己写了个例子,运行效果图如下。

标签可以左右滑动进行选择,点击的时候,会弹出toast提示选择或者取消选择了哪个标签。通过动态添加TextView作为标签,并给TextView设置背景,通过selector选择器改变其背景颜色,来确定是否处于选中状态。
代码如下所示:
1、标签的布局文件,我在标签里只设置了一个TextView
<?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/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:background="@drawable/mark_select" android:enabled="false" android:padding="10dp" android:text="TextView" /> </LinearLayout>