單純的自定義一個圓非常簡單 只需要幾步就完成 拖動圓添加實現觸摸事件即可
我在第一次自定義View圓遇到的小問題:
1.拖動圓的話在xml裏面設置的自定義圓的寬和高是它能活動的空間的大小 不是圓控件的大小 如果你定義了100dp 拖動它的時候超過100dp這個距離這個圓就會看不見 就像下面這樣 如果想活動於整個屏幕直接給寬和高match_parent屬性就好了
2.在佈局裏自定的view會提示編譯 點擊Build編譯一下就好了
下面開始寫代碼: 先是單純的創建一個圓形 創建一個類繼承View 實現onDraw方法
public class CustomView extends View {
//創建point對象 參數爲x座標和y座標
private PointF point = new PointF(100, 100);
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//參數爲圓的橫座標 ,縱座標,半徑,創建
//如果圓形出不來 說明你xml裏定義的寬和高的空間不夠大 這裏是圓在屏幕的座標位置 xml定義的是圓能夠顯示的區域 如果你定義的太小 圓的座標又超過了這個區域 就會顯示不出來 xml裏定義寬和高充滿屏幕就可以了
canvas.drawCircle(point.x,point.y, 50, new Paint());
}
}
XML裏、自己定義的view類的名字:
<ydtx.bwie.com.xiangmu_project02.CustomView
android:layout_width="match_parent"
android:layout_height="match_parent" />
一個圓就這樣創建好了 直接運行就可以了 ManActivity裏什麼也不用改
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
下面是添加拖動圓的功能 非常簡單 實現觸摸監聽即可 代碼非常少 如下:
public class CustomView extends View {
//創建point對象 參數爲x座標和y座標
private PointF point = new PointF(100, 100);
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//參數爲圓的橫座標 ,縱座標,半徑,創建
//如果圓形出不來 說明你xml裏定義的寬和高的空間不夠大 這裏是圓在屏幕的座標位置 xml定義的是圓能夠顯示的區域 如果你定義的太小 圓的座標又超過了這個區域 就會顯示不出來 xml裏定義寬和高充滿屏幕就可以了
canvas.drawCircle(point.x,point.y, 50, new Paint());
}
//觸摸事件
@Override
public boolean onTouchEvent(MotionEvent event) {
//獲得觸摸事件
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
//ACTION_MOVE不要設置break,否則圓形不會跟隨手指活動 只會手指鬆開屏幕的時候圓形直接到了屏幕停止的位置
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
//獲取手指觸摸位置的x座標
point.x = event.getX();
//獲取手指觸摸位置的y座標
point.y = event.getY();
//啓動
postInvalidate();
break;
}
return true;
}
}
這樣圓就跟隨手指的活動而動了 快試試吧