日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android自定义控件增加xml标签属性、取值等

發布時間:2023/12/3 Android 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android自定义控件增加xml标签属性、取值等 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Android中常常用到寫自己的控件來滿足自己的開發需求,自定義控件在布局中使用的時候,如何增加標簽屬性來配置控件屬性,又如何在控件中使用自己添加的屬性


?

一、在資源文件中配置標簽屬性

在資源文件res/values/attrs.xml中增加?declare-styleable 節點,name為自定義控件名字;如下

<resources><declare-styleable name="CustomerView">//項目中資源id<attr name="background" format="reference" /><attr name="src" format="reference" />//顏色<attr name = "textColor" format = "color" /> //布爾值<attr name = "focusable" format = "boolean" /> //尺寸值 dp,sp,px等<attr name = "width" format = "dimension" />//字符串 <attr name = "textStr" format = "string" /> //枚舉值<attr name="orientation"> <enum name="horizontal" value="0" /> <enum name="vertical" value="1" /> </attr> </declare-styleable> </resources>

其中子節點attr中的name值backound、src、textColor、focusable、width、textStr均為范例,自己寫的時候自定義屬性名稱

二、xml布局文件的控件中引用自己定義的屬性

1、引入app的命名空間,自定義屬性以"app:"為前綴

<layout xmlns:app="http://schemas.android.com/apk/res-auto"><com.example.weiget.CustomerViewapp:textStr="@string/app_name"app:background="@string/app_name"android:src="@drawable/compile"android:layout_width="match_parent"android:layout_height="match_parent"/> </layout>

三、項目中自定義屬性和布局文件中的屬性值都配置好了,如何在自定義控件文件中拿到配置的參數呢;如
?

public class CustomerView extends AppCompatImageView {public CustomerView(Context context) {super(context);init(context,null);}public CustomerView(Context context, AttributeSet attrs) {super(context, attrs);init(context,attrs);}public CustomerView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);init(context,attrs);}private void init(Context context, AttributeSet attrs) {if(attrs != null) {//從項目style中文件中取出樣式數組TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomerView);//取到xml布局文件中配置的資源文件Drawable drawable = typedArray.getDrawable(R.styleable.CustomerView_src);//字符串String string = typedArray.getString(R.styleable.CustomerView_textStr);//布爾值boolean aBoolean = typedArray.getBoolean(R.styleable.CustomerView_focusable, false);}} }

從typeArray數組中取值的參數,其中參數命門規則為R.styleable.控件名_屬性名

?

?

?

?

?

?

?

?

總結

以上是生活随笔為你收集整理的Android自定义控件增加xml标签属性、取值等的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。