android开发中,常常需要为视图添加自定义属性以存储数据或控制视图行为。本文将详细讲解如何自定义TextView属性,并获取其值,从而避免在年龄筛选功能中使用android:tag属性。
开发者希望为年龄筛选按钮(多个TextView组成)添加自定义属性,以便在点击事件中获取每个TextView对应的年龄范围。为避免android:tag属性的冲突,我们采用自定义属性的方法。
首先,在attrs.xml文件中声明自定义属性:
<resources> <declare-styleable name="CustomTextView"> <attr format="string" name="ageRange" /> </declare-styleable> </resources>
这行代码声明了一个名为CustomTextView的可样式化属性集合,包含一个名为ageRange的字符串类型属性,用于存储年龄范围。
接下来,在布局文件中使用自定义属性:
<com.google.android.flexbox.flexboxlayout android:onClick="@{(view) -> vm.ageItemClickHandle(view)}" style="@style/fragment_home_drawer_flexbox"> <TextView android:layout_marginStart="0dp" android:text="不限" app:ageRange="" style="@style/fragment_home_drawer_search_item_text" /> <TextView android:text="18-25" app:ageRange="18-25" style="@style/fragment_home_drawer_search_item_text" /> </com.google.android.flexbox.flexboxlayout>
app:ageRange表示我们自定义的属性。每个TextView都通过app:ageRange设置了对应的年龄范围。
最后,在点击事件处理方法中,使用obtainStyledAttributes方法获取自定义属性的值:
public void ageItemClickHandle(View view) { if (view instanceof TextView) { TextView textView = (TextView) view; TypedArray typedArray = textView.getContext().obtainStyledAttributes(textView, R.styleable.CustomTextView); String ageRange = typedArray.getString(R.styleable.CustomTextView_ageRange); typedArray.recycle(); // ... 使用 ageRange 进行年龄筛选操作 ... } }
代码首先判断点击视图是否为TextView,然后使用obtainStyledAttributes获取CustomTextView属性集合,并通过getString方法获取ageRange属性值。最后,调用recycle()方法回收资源。 这样就成功获取了自定义属性值,实现了年龄筛选功能,并避免了使用android:tag属性。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END