android 自訂群組件隨著手指自動畫圓

來源:互聯網
上載者:User

android 自訂群組件隨著手指自動畫圓

首先自訂一個View子類:

package com.example.androidtest0.myView;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;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);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);//設定畫筆的顏色p.setColor(Color.RED);//繪製一個小球canvas.drawCircle(currentX, currentY, 15, p);}/** * 為該組件的觸碰事件重寫事件處理方法 */@Overridepublic boolean onTouchEvent(MotionEvent event) {//修改currentX、currentY兩個屬性currentX = event.getX();currentY = event.getY();//通知當前組件重繪自己invalidate();return true;}    }

主介面XML:

custom_layout.xml




主activity:

package com.example.androidtest0;import com.example.androidtest0.myView.DrawView;import android.app.Activity;import android.os.Bundle;import android.widget.LinearLayout;public class CustomView extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.custom_layout);//擷取布局檔案中LinearLayout容器LinearLayout root = (LinearLayout)findViewById(R.id.root);//建立DrawView組件final DrawView drawView = new DrawView(this);//設定自訂群組件的最小寬度、高度drawView.setMinimumWidth(10);drawView.setMinimumHeight(10);root.addView(drawView);}}
效果:



<喎?http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+s/20y9auzeKjujwvcD4KPHA+u7m/ydLU08NYTUy1xLe9yr2jutKyysfK18/IvajSu7j2Vmlld7XE19PA4KOsus3Jz8Pm0rvR+aGjyLu689b3vefD5lhNTMjnz8KjujwvcD4KPHA+PHByZSBjbGFzcz0="brush:java;">


主activity檔案如下:

package com.example.androidtest0;import com.example.androidtest0.myView.DrawView;import android.app.Activity;import android.os.Bundle;import android.widget.LinearLayout;public class CustomView extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.custom_layout);}}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.