簡單自訂View,自訂view

來源:互聯網
上載者:User

簡單自訂View,自訂view

簡單的自訂View下,參考李剛瘋狂Andriod

package com.utils.MyDemo;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.view.View;public class MyView extends View {public float currentX=40;public float currentY=40;public MyView(Context context) {super(context);}public MyView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);// TODO Auto-generated constructor stub}public MyView(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stub}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);Paint paint=new Paint();paint.setColor(Color.GREEN);canvas.drawCircle(currentX, currentX, 15, paint);}}
主要需要重新父類構造方法,幾個方法切記不要刪除。

在XML引用如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >    <com.utils.MyDemo.MyView       android:id="@+id/myView"        android:layout_height="wrap_content"         android:layout_width="wrap_content"     />   </LinearLayout>

主要是全稱,包名+類名

在Activity中修改

public class MainActivity extends Activity {    /** Called when the activity is first created. */private MyView myView=null;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        myView=(MyView)this.findViewById(R.id.myView);        myView.setMinimumHeight(500);        myView.setMinimumWidth(300);        myView.setOnTouchListener(new View.OnTouchListener() {public boolean onTouch(View arg0, MotionEvent event) {myView.currentX=event.getX();myView.currentY=event.getY();myView.invalidate();return true;}});    }}

以上自訂MyView 主要完成了,隨滑鼠點擊移動事件,MyView 為圓形隨之運動。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.