android 自定义属性步骤

一个程序能否吸引用户,漂亮的UI和优秀的交互是至关重要的因素。因此现在大多数应用不满足了系统提供好的UI组件,而使用自定义组件来达到更好的显示效果。使用自定义组件大多数情况又会使用自定义属性。本文记录了自定义属性的几个步骤:

1.规划好自已需要定义的属性名字及类型

2.在res/values目录下新建一个attrs.xml; 将之前规划好的属性定义在attrs.xml中。具体如下:

1 <declare-styleable name="MyTextView">
2     <attr name="textColor" format="color"/>
3     <attr name="textSize" format="dimension"/>
4     <attr name="text" format="string"/>
5     <attr name="background" format="reference|color"/>
6 </declare-styleable>

3.属性定义好了,需要在自定义View中,主要是构造方法中获取自定义的属性的值 ,以供我们实现自定义view的需要。自定义属性使用R.styleable引用,获取里面的属性需要使用“名字_属性”的方式。TypeArray在使用完成后要进行recycle().如下所示:

 1 public MyTextView(Context context, AttributeSet attrs) {
 2         super(context, attrs);
 3         mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
 4         TypedArray typeArray = context
 5                 .obtainStyledAttributes(attrs, R.styleable.MyTextView);
 6 
 7         mTextColor = typeArray.getColor(R.styleable.MyTextView_textColor, Color.BLACK);
 8         mTextSize = typeArray.getDimension(R.styleable.MyTextView_textSize, 14);
 9         mText = typeArray.getString(R.styleable.MyTextView_text);
10         
11         mTextBackground = typeArray.getColor(R.styleable.MyTextView_background, Color.WHITE);
12         
13         mTextPaint.setColor(mTextColor);
14         mTextPaint.setTextSize(mTextSize);
15         mTextPaint.setTypeface(Typeface.DEFAULT);
16         
17         typeArray.recycle();
18     }

4.实现好自定义view,然后就是使用自定义view,在xml中设置我们定义的自定义的view的值。如下所示:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:mytextview = "http://schemas.android.com/apk/res/com.example.viewdemo"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     android:orientation="vertical" >
 7     
 8     <com.example.view.textview.MyTextView 
 9         android:layout_width="500dp"
10         android:layout_height="wrap_content"
11         mytextview:text="my name is text view , i am a text view"
12         mytextview:textSize="20sp"
13         mytextview:textColor="#000000"
14         mytextview:background="#ffffff"
15         />
16 
17 </LinearLayout>

需格外注意上在标红的语句。要设置xmlns来引用我们上面定义的自定义属性,命名空间为“mytextview”值为“http://schemas.android.com/apk/res/”+包名“com.example.viewdemo”。然后下面自定义view的tag里面使用命名空间:属性名的方式对自定义的属性进行赋值。

如此,我们的自定义属性即完成,便可以在自定义view中获取属性值,进行使用。

原文地址:https://www.cnblogs.com/pillowzhou/p/4665287.html