android自定义view

上一篇 / 下一篇  2013-09-30 08:55:06 / 个人分类:step by step android测试

学习地址:http://blog.chinaunix.net/uid-26885609-id-3479671.html
很多时候系统自带的View满足不了设计的要求,就需要自定义View控件。自定义View首先要实现一个继承自View的类。添加类的构造方法,override父类的方法,如onDraw,(onMeasure)等。

public class MyView extends TextView{

    public MyView(Context context) {

       super(context);

       // TODO Auto-generated constructor stub

    }

}

1、直接使用
setContentView(new MyView(this));
2、如果要在布局文件中用到,还需要添加一个构造方法:

public MyView(Context context,AttributeSet attrs){

       super(context, attrs);  

    }

3、实现自定义View的属性设置

  需要:

1)在values目录下建立attrs.xml文件,添加属性内容

2)在布局文件中添加新的命名空间xmlns,然后可以使用命名空间给自定义的空间设置属性

3)设置完属性之后,当然还要对其进行处理。在自定义View类中的构造方法中进行处理

1)values目录下建立attrs.xml文件,添加属性内容

<resources> 

    <declare-styleable name="MyView"> 

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

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

    </declare-styleable> 

</resources>

2)在布局文件中添加新的命名空间xmlns,然后可以使用命名空间给自定义的空间设置属性

xmlns:my=http://schemas.android.com/apk/res/com.example.xhelloworld

<com.example.xhelloworld.MyView 

       android:layout_width="fill_parent" 

       android:layout_height="wrap_content"   

       my:textColor="#FFFFFFFF"   

       my:textSize="22dp" 

    /> 

注:这步我在实现的时候出错,问题是显示找不到属性textColortextSize,这奇怪的错误。解决方法是,在写my:textColor="#FFFFFFFF" 时,写到my之后,按alt+/,这是会自动添加一个xmlns,和my的路径是一样的,用生成的这个替换掉my就可以了。

3)设置完属性之后,当然还要对其进行处理。在自定义View类中的构造方法中进行处理

public MyView(Context context,AttributeSet attrs){

       super(context, attrs);

         mPaint = new Paint();  

        //TypedArray是一个用来存放由context.obtainStyledAttributes获得的属性的数组  

        //在使用完成后,一定要调用recycle方法  

        //属性的名称是styleable中的名称+“_”+属性名称  

        //TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);

        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);

        int textColor = array.getColor(R.styleable.MyView_textColor, 0XFF00FF00); //提供默认值,放置未指定  

        float textSize = array.getDimension(R.styleable.MyView_textSize, 36);  

        mPaint.setColor(textColor);  

        mPaint.setTextSize(textSize);  

        array.recycle(); //一定要调用,否则这次的设定会对下次的使用造成影响  

      

    }

4、背后的事

View类的构造方法:

·public viewContext context       当在代码中创建对象时会被调用

·public View (Context context, AttributeSet attrs)

官方的文档是:

Constructor that is called when inflating a view from XML. This is called when a view is being constructed from an XML file, supplying attributes that were specified in the XML file. This version uses a default style. of 0, so the only attribute values applied are those in the Context's Theme and the given AttributeSet

大致应该是这个方法是通过xml文件来创建一个view对象的时候调用。很显然xml文件一般是布局文件,就是现实控件的时候调用,而布局文件中免不了会有属性的设置,如androidlayout_width等,对这些属性的设置对应的处理代码也在这个方法中完成。




TAG:

 

评分:0

我来说两句

Open Toolbar