所有的布局类和视图类都是继承View类。
当Android系统提供的一些View子类不能满足需求的时候,就需要自定义个View子类。
方法1: 直接继承View类
方法2: 继承View类的一个子类,例如:如果需要一个带有图像的TextView类,自定义类就可以直接去继承TextView类。
MyView类
package com.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View{
private static final String namespace = "http://schemas.android.com/apk/res/android";
private String mText;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
mText = attrs.getAttributeValue(namespace, "text");
if(mText == null) {
mText="";
}
}
@Override
protected void onDraw(Canvas canvas) {
Paint p = new Paint();
p.setColor(Color.WHITE);
p.setTextSize(30);
canvas.drawText(mText, 100, 100,p);
super.onDraw(canvas);
}
public String getmText() {
return mText;
}
public void setmText(String mText) {
this.mText = mText;
}
}
View类有三个构造方法,这里只实现了其中的一个带2个参数的构造,因为当在程序中,使用findViewById(id)获得组件实例的时候,调用的是带有2个参数的构造方法。
使用第二个参数的一些方法,可以在自定义类设定自己的属性,去XML文件里面定义的属性去找。
namespace为命名空间不多解释。
使用命名空间和不使用命名空间的区别:
mText = attrs.getAttributeValue(namespace, "text");
这里使用了命名空间,则在给mText赋值的时候,相对应于xml中的 android:text="呵呵呵呵"
mText = attrs.getAttributeValue(null, "texttext");
如果未使用命名空间,相对应xml中的 texttext="呵呵呵呵"
补上main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.view.MyView
android:id="@+id/mtext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="呵呵呵呵"
/>
</LinearLayout>
本文详细介绍了如何通过直接继承View类或继承View类的子类来自定义Android UI组件,包括创建MyView类的过程,展示了如何利用XML属性进行配置,并提供了完整的示例代码。同时,解释了命名空间在获取属性值时的作用,以及如何在main.xml文件中正确配置自定义视图。
32

被折叠的 条评论
为什么被折叠?



