今天学习了一些安卓开发中的自定义布局,编写了简单一个实例,“跟随手指移动的鸟”,需要两张图片,背景图片和鸟的图片,鸟的图片可以在屏幕中跟随手指的移动而移动。
1.将两张图片导入到mipmap中;
2.首先设置背景,用到了background方法,并设置其id;
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="16dp" android:paddingLeft="16dp" android:paddingRight="16dp" android:paddingTop="16dp" android:background="@mipmap/background" android:id="@+id/aaa" tools:context=".MainActivity"> </FrameLayout>
3.编写java代码继承View,设置鸟的图片的默认显示位置,bitmapx和bitmapy,分别为x坐标和y坐标,然后重写onDraw方法
package com.example.myview; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.view.View; public class BirdView extends View{ public float bitmapx; public float bitmapy; public BirdView(Context context) { super(context); bitmapx=290; bitmapy=130; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint=new Paint(); Bitmap bitmap=BitmapFactory.decodeResource(this.getResources(),R.mipmap.bird1); canvas.drawBitmap(bitmap,bitmapx,bitmapy,paint); if (bitmap.isRecycled()){ bitmap.recycle(); } } }
3.编写主方法,并测试结果。
package com.example.myview; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FrameLayout frameLayout=(FrameLayout) findViewById(R.id.aaa); final BirdView birdView=new BirdView(this); birdView.setOnTouchListener(new View.OnTouchListener() { //触摸动作监听 @Override public boolean onTouch(View view, MotionEvent motionEvent) { birdView.bitmapx= motionEvent.getX(); birdView.bitmapy=motionEvent.getY(); birdView.invalidate(); return true; } }); frameLayout.addView(birdView); } }