2012-08-03 246 views
1

我需要一個示例代碼,當我們從左到右和從右到左移動(觸摸)圖像時。請幫幫我。移動圖像與觸摸事件

問候,

+3

和,你有什麼相同的嘗試? – Lucifer 2012-08-03 06:35:13

+1

瞭解如何使用手勢檢測實現ViewFlipper .. – 2012-08-03 06:39:22

+0

我是第一次開發遊戲,我不知道它是如何工作的因此,通過示例代碼,我可以很容易地理解它。這就是我問的原因。 – Chakri 2012-08-03 12:53:52

回答

8

試試這個代碼...

這是你的主要活動類

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

import android.widget.ImageView; 
import android.widget.LinearLayout.LayoutParams; 
import android.widget.RelativeLayout; 
import android.support.v4.app.NavUtils; 

public class MainActivity extends Activity { 

    ImageView imageView; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     imageView = (ImageView)findViewById(R.id.imageView1); 

     imageView.setOnTouchListener(new OnTouchListener() { 

      public boolean onTouch(View v, MotionEvent event) { 
       // TODO Auto-generated method stub 
       int eid = event.getAction(); 
       switch (eid) { 
       case MotionEvent.ACTION_MOVE: 

        RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams(); 
        int x = (int) event.getRawX(); 
        int y = (int) event.getRawY(); 
        mParams.leftMargin = x-50; 
        mParams.topMargin = y-50; 
        imageView.setLayoutParams(mParams); 


        break; 

       default: 
        break; 
       } 
       return true; 
      } 
     }); 
    } 




} 

main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:layout_marginLeft="126dp" 
     android:layout_marginTop="168dp" 
     android:src="@drawable/ic_launcher" /> 

</RelativeLayout> 
+0

它的工作正常。但是,雖然拖動圖像它將遠離我的cursr點如何解決這個@Mehul – vijay 2014-12-06 10:22:52