2012年7月25日 星期三

(Android Note) 拖曳圖片

1. 說明: 拖曳icon, 並且記錄 icon目前位置

2. Drag_Drop.java

package com.kochi.knowhow;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class Drag_Drop extends Activity {
    /** Called when the activity is first created. */
private ImageView img;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drag_drop);
        img = (ImageView)findViewById(R.id.dragdropImageView1);
        img.setOnTouchListener(imgListener);
    }
 
    private OnTouchListener imgListener = new OnTouchListener(){
    private float x, y; //原本圖片存在的X,Y軸位置
    private int mx, my; //圖片被拖曳的X ,Y軸距離長度
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
//Log.e("View", v.toString());
switch(event.getAction()) {  
//按下圖片時
case MotionEvent.ACTION_DOWN:  
                x = event.getX();  
                y = event.getY();
            //移動圖片時
            case MotionEvent.ACTION_MOVE:  
                mx = (int)(event.getRawX() - x);  
                my = (int)(event.getRawY() - 50 - y); //50應該是標題框長度
                v.layout(mx, my, mx + v.getWidth(), my + v.getHeight());  
                break;  
            }
Log.e("address", String.valueOf(mx)+"~~"+String.valueOf(my)); //記錄目前位置
            return true;  
}
    };
}

3. drag_drop.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
 <ImageView android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:src="@drawable/icon"
    android:id="@+id/dragdropImageView1"></ImageView>

</LinearLayout>






沒有留言:

張貼留言