2013-02-19 93 views
0

我在我的佈局中有一個imageview和一個textview,我想要移動此touchview觸摸。它的工作,但問題是textview的移動,你能告訴我如何解決它?Android拖動圖像

這是我的代碼

private ImageView img; 
private int status=0; 
TextView tv; 
RelativeLayout.LayoutParams params; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    img=(ImageView)findViewById(R.id.imageView1); 
    img.setOnTouchListener(new View.OnTouchListener() { 

     @Override 
     public boolean onTouch(View arg0, MotionEvent arg1) { 
      // TODO Auto-generated method stub 

      status=1; 

     return false; 
     } 
    }); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.activity_main, menu); 

    return false; 
} 


@Override 
public boolean onTouchEvent(MotionEvent event) { 
// TODO Auto-generated method stub 

    if(status==1) 
    { 
     LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); 
     lp.topMargin=(int)event.getRawY(); 
     lp.leftMargin=(int)event.getRawX(); 
     img.setLayoutParams(lp); 
    } 
    if(event.getAction()==MotionEvent.ACTION_UP){ 
    status=0; 
    } 
return super.onTouchEvent(event); 

} }

這是我的XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/LinerLayout" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context=".MainActivity" > 

<ImageView 
    android:id="@+id/imageView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentBottom="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginBottom="84dp" 
    android:src="@drawable/ic_launcher" /> 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/imageView1" 
    android:layout_alignParentTop="true" 
    android:layout_marginTop="119dp" 
    android:text="TextView" /> 

+0

請註明您的佈局 – 2013-02-19 15:53:15

+0

的XML文件,當您刪除行,會發生什麼:機器人:layout_alignLeft =「@ + ID/imageView1」 – 2013-02-19 15:56:30

+0

是的,我知道了,我意識到這一點時,我打開我的XML,謝謝@T Dezentje – 2013-02-19 15:58:23

回答

0

名偵探柯南,OMG我忘了,因爲我使用相對佈局文本視圖左對齊imageview1 感謝您的幫助