会跟随手指动起来的小机器人

1、先写个帧布局

<FrameLayout xmlns:android="<a href="http://schemas.android.com/apk/res/android"">http://schemas.android.com/apk/res/android"
    xmlns:tools="<a href="http://schemas.android.com/tools"">http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/mylayout"
    >

</FrameLayout>

2、自定义一个RabbitView类,继承View.

package com.example.moverabbit;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;

@SuppressLint("DrawAllocation")
public class RabbitView extends View {
    public float bitmapX;
    public float bitmapY;
    public RabbitView(Context context) {
        super(context);
        bitmapX=750;//机器人初始位置
        bitmapY=500;
    }

@SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint=new Paint();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        canvas.drawBitmap(bitmap, bitmapX,bitmapY, paint);//重点在这里!
        if(bitmap.isRecycled()){
            bitmap.recycle();//强制回收
        }
    }

}

3、在MainActivity中,直接先找到容器,再new自定义控件的对象,将自定义的view添加进容器中。如果想让它动起来的话,直接监听这个自定义对象的onTouchListener的动作,当在touch事件里面不断捕捉到手指的移动时,并重新赋值给机器人的坐标,就会使机器人的位置不断变化。

代码如下:

package com.example.moverabbit;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FrameLayout mylayout = (FrameLayout) this.findViewById(R.id.mylayout);
        final RabbitView rabbitView=new RabbitView(this);
        mylayout.addView(rabbitView);//代码动态添加组件
        rabbitView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                rabbitView.bitmapX=event.getX()-25;
                rabbitView.bitmapY=event.getY()-25;//设置它的位置
                rabbitView.invalidate();//重新刷新组件,更改位置
                return true;
            }
        });
    }
}

最终效果图:

8

 

完整demo地址:

      http://download.csdn.net/detail/together011/8947925  不喜勿喷。

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值