Android自定义控件增加xml标签属性、取值等
生活随笔
收集整理的這篇文章主要介紹了
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标签属性、取值等的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sqlite数据库查询语句,数据库中是否
- 下一篇: 2020-12-04使用retrofit