定義view  

 


 

 

1.先在XML創建一個myview的xml記得要選view

2.在java新增一個Myview的(class) extends View

3.寫完再xml左邊調色板下面自訂義就會有自訂義的View了,再加入


 

public class Myview extends View{

Activity activity;//因為要setTitle所以要把activity因為view不能setTitle

Bitmap bit[]=new Bitmap[4];
int bitmap[]={R.drawable.c1,R.drawable.c2,R.drawable.c3,R.drawable.c4};

public Myview(Context context, AttributeSet attrs) {
super(context, attrs);
activity=(Activity) context;
// bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.c1);
// //把圖片放進去自訂義的view要用bitmap

for(int i=0;i<bit.length;i++)
{
bit[i]=BitmapFactory.decodeResource(getResources(), bitmap[i]);
}


}
// 自己畫一個view、複寫這個方法、右鑑選source--override----onDraw()
@Override
protected void onDraw(Canvas canvas) {

Paint paint = new Paint();
//有畫布也要有畫筆所以要new paint
canvas.drawCircle(100, 100, 50, paint);
//例如:劃一個圓,drawCircle(x,y,半徑,畫筆);



canvas.drawBitmap(bit[0],200,300, paint);
canvas.drawBitmap(bit[1],220,100, paint);
canvas.drawBitmap(bit[2],150,80, paint);
canvas.drawBitmap(bit[3],400,200, paint);
//利用canvas把圖片放進去
super.onDraw(canvas);
}

//抓取按壓,彈起,平移的座標
@Override
public boolean onTouchEvent(MotionEvent event) {

int x=(int) event.getX();
//取x軸座標
int y=(int) event.getY();
//取y軸座標
int action =event.getAction();
//取整數
switch(action)
{
case MotionEvent.ACTION_DOWN:

activity.setTitle("Down:"+x+","+y);
break;

case MotionEvent.ACTION_MOVE:
activity.setTitle("MOVE平移:"+x+","+y);
break;
case MotionEvent.ACTION_UP:
activity.setTitle("UP:"+x+","+y);
break;
}




return true;//super.onTouchEvent(event);
//要改為true
}

}

 


myview.xml

<?xml version="1.0" encoding="utf-8"?>

<com.example.gujn_0515.Myview //要加入Myview的路徑名+檔名才能定義

xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

</com.example.gujn_0515.Myview> //要加入Myview的路徑名+檔名才能定義

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 小Chiu 的頭像
    小Chiu

    Cuiu's Home

    小Chiu 發表在 痞客邦 留言(0) 人氣()