您好,登錄后才能下訂單哦!
小編給大家分享一下Android如何實(shí)現(xiàn)自定義View圓形和拖動(dòng)圓、跟隨手指拖動(dòng)效果,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
單純的自定義一個(gè)圓非常簡(jiǎn)單 只需要幾步就完成 拖動(dòng)圓添加實(shí)現(xiàn)觸摸事件即可
我在第一次自定義View圓遇到的幾個(gè)Bug:
1.拖動(dòng)圓的話(huà)在xml里面設(shè)置的自定義圓的寬和高是它能活動(dòng)的空間的大小 不是圓控件的大小 如果你定義了100dp 拖動(dòng)它的時(shí)候超過(guò)100dp這個(gè)距離這個(gè)圓就會(huì)看不見(jiàn) 就像下面這樣 如果想活動(dòng)于整個(gè)屏幕直接給寬和高match_parent
屬性就好了
2.我在定義充滿(mǎn)屬性match_parent
的時(shí)候運(yùn)行會(huì)報(bào)錯(cuò),什么方法都用了就是不行,耐心等待過(guò)一會(huì)就好了…有可能是studio沒(méi)來(lái)得及編譯過(guò)來(lái)
下面開(kāi)始寫(xiě)代碼: 先是單純的創(chuàng)建一個(gè)圓形 創(chuàng)建一個(gè)類(lèi)繼承View 實(shí)現(xiàn)onDraw方法
public class CustomView extends View { //創(chuàng)建point對(duì)象 參數(shù)為x坐標(biāo)和y坐標(biāo) 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); //參數(shù)為圓的橫坐標(biāo) ,縱坐標(biāo),半徑,創(chuàng)建 canvas.drawCircle(point.x,point.y, 50, new Paint()); } }
XML里、自己定義的view類(lèi)的名字:
<ydtx.bwie.com.xiangmu_project02.CustomView android:layout_width="match_parent" android:layout_height="match_parent" />
一個(gè)圓就這樣創(chuàng)建好了 直接運(yùn)行就可以了 ManActivity里什么也不用改
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }
下面是添加拖動(dòng)圓的功能 非常簡(jiǎn)單 實(shí)現(xiàn)觸摸監(jiān)聽(tīng)即可 代碼非常少 如下:
public class CustomView extends View { //創(chuàng)建point對(duì)象 參數(shù)為x坐標(biāo)和y坐標(biāo) 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); //參數(shù)為圓的橫坐標(biāo) ,縱坐標(biāo),半徑,創(chuàng)建 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不要設(shè)置break,否則圓形不會(huì)跟隨手指活動(dòng) 只會(huì)手指松開(kāi)屏幕的時(shí)候圓形直接到了屏幕停止的位置 case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_UP: //獲取手指觸摸位置的x坐標(biāo) point.x = event.getX(); //獲取手指觸摸位置的y坐標(biāo) point.y = event.getY(); //啟動(dòng) postInvalidate(); break; } return true; } }
看完了這篇文章,相信你對(duì)“Android如何實(shí)現(xiàn)自定義View圓形和拖動(dòng)圓、跟隨手指拖動(dòng)效果”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。