android開發中,自定義視圖屬性并獲取其值能顯著提升代碼的可讀性和可維護性。本文將詳細介紹如何自定義TextView屬性value,并演示如何在年齡篩選場景中獲取該屬性值。 由于android:tag屬性可能被占用,我們選擇自定義屬性存儲年齡范圍信息。
首先,在res/values/attrs.xml文件中聲明自定義屬性(若文件不存在,需手動創建):
<resources> <declare-styleable name="CustomTextView"> <attr name="value" format="string" /> </declare-styleable> </resources>
然后,在布局文件中使用自定義屬性。app:前綴表示自定義屬性:
<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:value="" style="@style/fragment_home_drawer_search_item_text"/> <TextView android:text="18-25" app:value="18-25" style="@style/fragment_home_drawer_search_item_text"/> </com.google.android.flexbox.flexboxlayout>
最后,在代碼中,通過obtainStyledAttributes方法獲取自定義屬性值。在點擊事件處理函數ageItemClickHandle中:
public void ageItemClickHandle(View view) { if (view instanceof TextView) { TextView textView = (TextView) view; TypedArray typedArray = textView.getContext().obtainStyledAttributes(textView, R.styleable.CustomTextView); String value = typedArray.getString(R.styleable.CustomTextView_value); typedArray.recycle(); // 使用獲取到的value值 } }
通過以上步驟,即可自定義TextView屬性并獲取其值,實現靈活的年齡篩選功能。 記住在使用完TypedArray后調用recycle()方法釋放資源。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END