通常不实用View和ViewGroup类
可以使用继承View的自定义的View类
思路是:
创建继承View的自定义类, 在MainActivity.java 中创建自定义类的对象
实践--跟随手指移动的小兔子
XML : 设置背景图片, id
1 <?xml version="1.0" encoding="utf-8"?> 2 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:id="@+id/mylayout" 6 android:layout_width="match_parent" 7 android:layout_height="match_parent" 8 android:background="@mipmap/earth" 9 tools:context=".MainActivity"> 10 11 </FrameLayout>
创建Rabbit类
1 package com.example.myview; 2 3 import android.content.Context; 4 import android.graphics.Bitmap; 5 import android.graphics.BitmapFactory; 6 import android.graphics.Canvas; 7 import android.graphics.Paint; 8 import android.view.View; 9 10 public class RabbitView extends View { 11 public float bitmapX; 12 public float bitmapY; 13 public RabbitView(Context context) { 14 super(context); 15 bitmapX = 290; 16 bitmapY = 130; 17 } 18 19 @Override 20 protected void onDraw(Canvas canvas) { 21 super.onDraw(canvas); 22 Paint paint = new Paint(); // 创建画笔对象 23 Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.mipmap.robbit); // 设置图像, 将兔子图片作为参数传入 24 canvas.drawBitmap(bitmap, bitmapX, bitmapY, paint); // 通过canvas组件画出兔子 25 if(bitmap.isRecycled()) { // 回收 26 bitmap.recycle(); 27 } 28 } 29 }
在MainActivity.java类中创建Rabbit类的对象并设置Touch事件
1 package com.example.myview; 2 3 import android.support.v7.app.AppCompatActivity; 4 import android.os.Bundle; 5 import android.view.MotionEvent; 6 import android.view.View; 7 import android.widget.FrameLayout; 8 9 public class MainActivity extends AppCompatActivity { 10 11 @Override 12 protected void onCreate(Bundle savedInstanceState) { 13 super.onCreate(savedInstanceState); 14 setContentView(R.layout.activity_main); 15 FrameLayout frameLayout = findViewById(R.id.mylayout); 16 final RabbitView rabbitView = new RabbitView(this); 17 rabbitView.setOnTouchListener(new View.OnTouchListener() { 18 @Override 19 public boolean onTouch(View v, MotionEvent event) { 20 rabbitView.bitmapX = event.getX(); 21 rabbitView.bitmapY = event.getY(); 22 rabbitView.invalidate(); 23 return true; 24 } 25 }); 26 frameLayout.addView(rabbitView); 27 } 28 }