我想自己设计个view类,然后添加到xml布局里,最后显示在一个activity里,有人这样设计过吗,请赐教下

解决方案 »

  1.   

    1. 自定义View类public class MyView extends View{
            
    public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    }        //重载绘图方法
    @Override
    public void draw(Canvas canvas) {
    }
    }
    2. xml 布局。将定义的View类像普通控件一样添加进来,控件名即完整的包名+类名<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="wrap_content">  <Button android:layout_width="wrap_content" android:text="true" android:layout_height="wrap_content" android:id="@+id/btnTrue" android:layout_alignParentLeft="true"></Button>  <android.HelloTest.MyView 
        android:id="@+id/panWhite" android:layout_below="@id/lblMessage" 
        android:layout_width="match_parent" android:layout_height="200px" />
    </RelativeLayout>
    3. Activity 中使用
       跟普通控件一样,setContentView 之后findViewById 就行
       this.setContentView(R.layout.touchtest);
       MyView panWhite = (MyView)this.findViewById(R.id.panWhite);
      

  2.   

    和相对布局没关系,线性布局也可以用。
    参考:android自定义View的用法