Android简单实现自定义View

来源:互联网 发布:ipad淘宝开网店教程 编辑:程序博客网 时间:2024/05/10 06:54

1.创建View类继承View或者View的子类,并继承构造方法。

2.自定义属性

<?xml version="1.0" encoding="utf-8"?><resources><!--  名字随便起--> <declare-styleable name="MyViewStyleName" ><attr name="des" format="string" /><attr name="textColor" format="color"/><attr name="bgColor" format="color"/></declare-styleable></resources>

3.构造函数中获取属性,然后就可以使用属性在onDraw中绘画自己的View了,如设置画布背景颜色,字体颜色等

public MyView(Context context, AttributeSet attrs) {super(context, attrs);TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyViewStyleName);if(typedArray != null){/** * 获取xml中自定义属性des */mDes = typedArray.getString(R.styleable.MyViewStyleName_des);/** * 获取xml中自定义属性bgColor */mBackground = typedArray.getColor(R.styleable.MyViewStyleName_bgColor, Color.RED);/** * 获取xml中自定义属性textColor */mTextColor = typedArray.getColor(R.styleable.MyViewStyleName_textColor, Color.WHITE);}//initView();}

4.布局中使用自定义的View,并使用自己定义的属性

    <com.example.testdemo.MyView         xmlns:app="http://schemas.android.com/apk/res-auto"        android:layout_centerInParent="true"        app:des="这是自定义View内容"app:textColor="#ffffff"app:bgColor="#4cd964"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        />




原创粉丝点击