Android自定义View全面总结

来源:互联网 发布:国内餐饮软件排名 编辑:程序博客网 时间:2024/04/30 15:47
日积月累第四周第一天。短短清明三天小假期就这么结束了,学习还是要继续。。。
Android自定义View实现很简单


继承View,重写构造函数、onDraw,(onMeasure)等函数。


如果自定义的View需要有自定义的属性,需要在values下建立attrs.xml。在其中定义你的属性。


在使用到自定义View的xml布局文件中需要加入xmlns:前缀="http://schemas.android.com/apk/res/你的自定义View所在的包路径".


在使用自定义属性的时候,使用前缀:属性名,如my:textColor="#FFFFFFF"。


实例:
package demo.view.my;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.View;
/**
 * 这个是自定义的TextView.
 * 至少需要重载构造方法和onDraw方法
 * 对于自定义的View如果没有自己独特的属性,可以直接在xml文件中使用就可以了
 * 如果含有自己独特的属性,那么就需要在构造函数中获取属性文件attrs.xml中自定义属性的名称
 * 并根据需要设定默认值,放在在xml文件中没有定义。
 * 如果使用自定义属性,那么在应用xml文件中需要加上新的schemas,
 * 比如这里是xmlns:my="http://schemas.android.com/apk/res/demo.view.my"
 * 其中xmlns后的“my”是自定义的属性的前缀,res后的是我们自定义View所在的包
 * @author Administrator
 *
 */
public class MyView extends View {

Paint mPaint; //画笔,包含了画几何图形、文本等的样式和颜色信息
public MyView(Context context) {
super(context);

}

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);
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(); //一定要调用,否则这次的设定会对下次的使用造成影响
}

public void onDraw(Canvas canvas){
super.onDraw(canvas);
//Canvas中含有很多画图的接口,利用这些接口,我们可以画出我们想要的图形
//mPaint = new Paint();
//mPaint.setColor(Color.RED);
mPaint.setStyle(Style.FILL); //设置填充
canvas.drawRect(10, 10, 100, 100, mPaint); //绘制矩形

mPaint.setColor(Color.BLUE);
canvas.drawText("我是被画出来的", 10, 120, mPaint);
}
}






<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="textColor" format="color"/>
<attr name="textSize" format="dimension"/>
</declare-styleable>
</resources>




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:my="http://schemas.android.com/apk/res/demo.view.my" 
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <demo.view.my.MyView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    my:textColor="#FFFFFFFF" 
    my:textSize="22dp"
    />
</LinearLayout>








一个简单的例子:
·新建一个MyView类,继承自TextView,并添加构造方法:
package com.example.xhelloworld;
import android.content.Context;
import android.widget.TextView;
public class MyView extends TextView{
    public MyView(Context context) {
       super(context);
       // TODO Auto-generated constructor stub
    }
}
·再在主activity中调用。方法是setContentView(new MyView(this));这句
package com.example.xhelloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class NewView extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_newview);
        setContentView(new MyView(this));
       
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_newview, menu);
        return true;
    }
}
运行后的结果为:


 
这样一个简单的自定义View就可以使用了。可以改变一下背景颜色,在MyView类中添加:
@Override
    protected void onDraw(Canvas canvas) {
       // TODO Auto-generated method stub
       super.onDraw(canvas);
       canvas.drawColor(Color.BLUE);
    }
即可完成。运行结果
 
 
上面的例子很简单,没有涉及到属性的添加。使用范围很小,不能在布局文件中使用。如果要在布局文件中用到,还需要添加一个构造方法:
public MyView(Context context,AttributeSet attrs){
       super(context, attrs);  
    }
当然,上面只是在code中做的修改,在xml文件(main.xml)中也需要进行如下操作:
<com.example.xhelloworld.NewView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
至少在xml文件中写上上面的内容。其中com.example.xhelloworld.NewView这句是需要显示的控件所代表的类。Com.example.xhelloworld是类的包名,NewView是类名。这个类肯定是继承自View的自定义类(其实就是,使我们自己写的,这是废话了。。。),可以是在工程中直接源码添加xxxx.java的,也可以是在libs目录下自己新添加的jar包里面的。如果是jar包里面的一个类,则路径就是jar包里面,这个类的路径。
完成上面的两步之后就可以在代码中实例化这个布局文件了
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //setContentView(new MyView(this));
显示的效果同上图。
下面介绍如何实现自定义View的属性设置。实现自定义View的属性设置,需要:
·在values目录下建立attrs.xml文件,添加属性内容
·在布局文件中添加新的命名空间xmlns,然后可以使用命名空间给自定义的空间设置属性
·设置完属性之后,当然还要对其进行处理。在自定义View类中的构造方法中进行处理
根据这三步给一个例子进行说明一下
首先添加attrs.xml文件,在定义属性
<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="MyView"> 
    <attr name="textColor" format="color"/> 
    <attr name="textSize" format="dimension"/> 
    </declare-styleable> 
</resources>
然后在布局文件中完成:
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" 
    /> 
注:这步我在实现的时候出错,问题是显示找不到属性textColor和textSize,这奇怪的错误。解决方法是,在写my:textColor="#FFFFFFFF" 时,写到my之后,按alt+/,这是会自动添加一个xmlns,和my的路径是一样的,用生成的这个替换掉my就可以了。奇葩的问题就用奇葩的方法解决。起初我也不知道怎么弄,瞎搞出来的。
最后在MyView.java中添加另一个构造方法,并添加代码来处理从xml中获得的属性
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(); //一定要调用,否则这次的设定会对下次的使用造成影响  
      
    }
 
完成之后就已经实现了自定视图的构造,自定义视图属性的添加很处理。现在完成的是一般的自定义视图,继承自TextView或者View等视图,也就是通过程序主UI线程完成更新的视图,如果是自定义SurfaceView,实现方法有所不同。
添加完之后肯定有很多疑问,自己去做可能还不能理解。这里再对上面操作进行解释说明。
背后的事
View类的构造方法:
·public view(Context 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文件一般是布局文件,就是现实控件的时候调用,而布局文件中免不了会有属性的设置,如android:layout_width等,对这些属性的设置对应的处理代码也在这个方法中完成。
两个参数
Context          The Context the view is running in, through which it can access the current theme, resources, etc.
Attrs              The attributes of the XML tag that is inflating the view
·public View (Context context, AttributeSet attrs,int defStyle)
Perform inflation from XML and apply a class-specific base style. This constructor of View allows subclasses to use their own base style when they are inflating. For example, a Button class's constructor would call this version of the super class constructor and supply R.attr.buttonStyle fordefStyle; this allows the theme's button style to modify all of the base view attributes (in particular its background) as well as the Button class's attributes.
看的不太懂,没用到,下放一下吧额
这就是为什么要添加上面的两个构造方法的原因。
0 0