Android实现动态任意拖动图片

来源:互联网 发布:淘宝网页版登陆首页 编辑:程序博客网 时间:2024/06/05 02:14

应用场景:小游戏

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来实现的。


0 0
原创粉丝点击