星空网 > 软件开发 > 操作系统

android 自定义属性步骤

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

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

2.在res/values目录下新建一个attrs.

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,在

 1 <??> 2 <LinearLayout ="http://schemas.android.com/apk/res/android" 3   = "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>

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

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




原标题:android 自定义属性步骤

关键词:Android

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流