自定义属性TypedArray

来源:互联网 发布:wemall商业版java源码 编辑:程序博客网 时间:2024/06/05 21:01

贴代码一: value下新建一个attrs.xml文件

<resources>    <declare-styleable name="mAttr">        <attr name="theContent" format="string" />        <attr name="theColor"  format="color" />        <attr name="theTextSize"  format="dimension" />    </declare-styleable></resources>


贴代码二:新建一个类mView extends View。在构造函数中用TypedArray取值

public class mView extends View {private Paint mPaint;private String theContent;public mView(Context context) {super(context);}public mView(Context context, AttributeSet attrs) {super(context, attrs);mPaint=new Paint();TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.mAttr);theContent=ta.getString(R.styleable.mAttr_theContent);int theColor=ta.getColor(R.styleable.mAttr_theColor, Color.BLUE);float theTextSize=ta.getDimension(R.styleable.mAttr_theTextSize, 18);//为什么这里testSize用float而不用int,因为Paint.setTextSize(float textSize)mPaint.setColor(theColor);mPaint.setTextSize(theTextSize);ta.recycle();}public mView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);    canvas.drawText(theContent, 100, 100, mPaint);}    }
贴代码三:xmlns:test="..../res/应用的包名" 而不是自定义view所在的包名。

 ps. 写test:的时候按alt+/未能自动补齐,而上个项目mooc网的教学中又可以自动补齐=。=

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:test="http://schemas.android.com/apk/res/com.example.typedarray"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="${relativePackage}.${activityClass}" >    <com.example.typedarray.mView         android:layout_width="match_parent"        android:layout_height="match_parent"        test:theContent="hello world"        test:theColor="#ff7704"        test:theTextSize="30sp"        /></RelativeLayout>


贴截图:







0 0
原创粉丝点击