自定義View

1、自定義類:DrawView

public class DrawView extends View
{
    public float currentX = 40;
    public float currentY = 50;

    Paint p = new Paint();

    public DrawView(Context context)
    {
        super(context);
    }

    public DrawView(Context context, AttributeSet attrs)
    {
        super(context, attrs);

    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        p.setColor(Color.RED);
        canvas.drawCircle(currentX,currentY,15,p);
    }

    @Override public boolean onTouchEvent(MotionEvent event)
    {
        currentX = event.getX();
        currentY = event.getY();
        invalidate();  //通知當前組件重新繪自己
        return true;
    }
}

注意:一定要有第二個構造方法,否則會報XML file line #10: Binary XML file line #10: Error inflating class com.ui.demo.custom.DrawView異常

2、對應的xml佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.ui.demo.custom.CustomView">

 <com.ui.demo.custom.DrawView
    android:id="@+id/test"
     android:layout_width="match_parent"
     android:layout_height="match_parent"/>
</LinearLayout>
3、啓動的activity

public class CustomView extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章