自定义TextView属性和设置TextView属性

来源:互联网 发布:重庆大学出版社淘宝网 编辑:程序博客网 时间:2024/05/22 05:25

自定义的Textview 继承 自 TextView 有四个构造方法,传不同的参数 主要有下面几步来实现自定义属性:

1.自定义类中的属性,这个必须和attrs.xml 里面的属性一一对应起来 ,attrs.xml可以在values 包下进行创建,可以在xml文件中设置自定义的属性(就跟设置TextView自带的属性一样的),只不过是通过自己写的代码实现了一个获取的机制.

    private String str;//值    private int textcolor;

也可以加上get/set方法 互通数据

    public String getStr() {        return str;    }    public void setStr(String str) {        this.str = str;    }
三个构造方法,Textview默认的是调用2个参数的构造方法

public MyTextView(Context context) {        super(context);    }    public MyTextView(Context context, @Nullable AttributeSet attrs) {        super(context, attrs);        //从attrs.xml 文件加载一个 叫MyImageView的declare-styleable 的对象        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);        //将attrs.xml 文件中的 imageview属性 与 类中的属性str关联        str = typedArray.getString(R.styleable.MyTextView_textvalue);        textcolor = typedArray.getColor(R.styleable.MyTextView_textcolor, Color.RED);        //回收typeArray        typedArray.recycle();        setTextColor(textcolor);        setTextSize(20);        setGravity(Gravity.CENTER);    }    public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }

在第二个方法中进行自定义的获取,attrs.xml文件中的属性与类中的自定义的对应起来

    <declare-styleable name="MyTextView">        <attr name="textvalue" format="string">        </attr>        <attr name="textcolor" format="color"/>    </declare-styleable>

最后在xml文件中设置属性就ok了。

<com.example.administrator.sildslipyang.View.MyTextView        android:layout_width="match_parent"        android:layout_height="100dp"        app:textvalue="hello,MyTextView"        android:id="@+id/mytext"        android:text="yanghzoa dsa sdadasda"        android:background="#faaaaa"        />

也可以在自定义的Textview里面添加一些点击事件