標籤:android 動態拖放 button
應用情境:小遊戲
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來實現的。
Android實現動態任意拖動圖片