Android实现动态任意拖动图片

这篇博客介绍了如何在Android应用中实现动态任意拖动图片的功能,通过使用Button代替ImageView,利用OnTouchListener监听触摸事件,结合button的layout属性和postInvalidate方法,实现了图片元素在屏幕上的拖动和停留。此技术在‘乌鸦喝水’小游戏的开发中得以应用。

应用场景:小游戏

android要实现动态任意拖放图片,使用imageview实现比较困难,在这里介绍一种使用button的方法:

1. 界面元素有任意个,用户操作选中一个在屏幕上拖动,拖动完成后图片元素停留在actionup的位置;

2. 首先在界面设置任意个button元素,并设置background:

<RelativeLayout android:id="@+id/main"
android:background="@drawable/bgall"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none"
android:listSelector="#00000000">

<Button android:id="@+id/btnFirst"
android:background="@drawable/pebble"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

。。。

3. 主activity需要implements OnTouchListener,       

 touchCrowListener = new OnTouchListener()
    {
    int[] temp = new int[] { 0, 0 };
    int oldxxx = 0;
    int oldyyy = 0;
    public boolean onTouch(View v, MotionEvent event) 
    {
    int eventaction = event.getAction();
    int x = (int) event.getRawX();
    int y = (int) event.getRawY();

         。。。。。。

   //----------------------------------------------------------------------------------------------
    v.layout(x - temp[0], y - temp[1], x + v.getWidth() - temp[0], y - temp[1] + v.getHeight());
    v.postInvalidate();

4. 使用button的特点是易于控制因为可以使用layout属性和postInvalidate方法,且background设置也能达到imageview的显示效果

以上功能在 乌鸦喝水 小游戏中有使用【http://openbox.mobilem.360.cn/index/d/sid/162210       http://zhushou.360.cn/detail/index/soft_id/162210】

乌鸦和小石子儿都是通过button+设置btton的background来实现的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值