天天看点

android自定义xmls文件属性

下面是一个简单的例子:

结构图:

android自定义xmls文件属性

myview.java

package kexc.myview;

import android.content.context;

import android.content.res.typedarray;

import android.util.attributeset;

import android.widget.textview;

public class myview extends textview {  

    private string mstring = "welcome to kesion's blog";

    public myview(context context, attributeset attrs) {

  super(context, attrs);

  typedarray a = context.obtainstyledattributes(attrs,  

                r.styleable.myview);

  int textcolor = a.getcolor(r.styleable.myview_textcolor,  

                0xffffffff);  

        float textsize = a.getdimension(r.styleable.myview_textsize, 36);  

        mstring = a.getstring(r.styleable.myview_title);

  settext(mstring);

  settextsize(textsize);

  settextcolor(textcolor);

 }

}

main.xml

<?xml version="1.0" encoding="utf-8"?>  

<linearlayout   

    android:orientation="vertical"  

    android:layout_width="fill_parent"  

    android:layout_height="fill_parent">  

 <textview    

     android:layout_width="fill_parent"   

     android:layout_height="wrap_content"   

     android:text="@string/hello"  

     />  

 <kexc.myview.myview 

     android:layout_height="fill_parent"

     test:title="wo shi text"

     test:textsize="20px"  

     test:textcolor="#fff"  

 />

</linearlayout>

属性文件 value/attrs.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>

 <declare-styleable name="myview">  

        <attr name="textcolor" format="color"/>  

  <attr name="textsize" format="dimension" />  

  <attr name="title" format="string"/>

 </declare-styleable>

</resources>

运行结果:

android自定义xmls文件属性

继续阅读