android 自定义控件属性步骤

来源:互联网 发布:C语言的算术表达式 编辑:程序博客网 时间:2024/06/11 22:26

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

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

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

<declare-styleable name="MyTextView">     <attr name="textColor" format="color"/>     <attr name="textSize" format="dimension"/>     <attr name="text" format="string"/>     <attr name="background" format="reference|color"/></declare-styleable>


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

public MyTextView(Context context, AttributeSet attrs) {          super(context, attrs);          mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);          TypedArray typeArray = context                  .obtainStyledAttributes(attrs, R.styleable.MyTextView);            mTextColor = typeArray.getColor(R.styleable.MyTextView_textColor, Color.BLACK);          mTextSize = typeArray.getDimension(R.styleable.MyTextView_textSize, 14);          mText = typeArray.getString(R.styleable.MyTextView_text);                  mTextBackground = typeArray.getColor(R.styleable.MyTextView_background, Color.WHITE);                  mTextPaint.setColor(mTextColor);         mTextPaint.setTextSize(mTextSize);         mTextPaint.setTypeface(Typeface.DEFAULT);                  typeArray.recycle();     }


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

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:mytextview = "http://schemas.android.com/apk/res/com.example.viewdemo"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical" >         <com.example.view.textview.MyTextView         android:layout_width="500dp"        android:layout_height="wrap_content"        mytextview:text="my name is text view , i am a text view"        mytextview:textSize="20sp"        mytextview:textColor="#000000"        mytextview:background="#ffffff"        /></LinearLayout>

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

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


0 0
原创粉丝点击