我在ImageView
中有一个Button
和一个LinearLayout
。我想在屏幕上拖动ImageView
,但保留Button
。但出于某种原因,当我拖动ImageView
Button
拖拽它时。
有人可以帮忙吗?
代码:
activity_main.xml中
<LinearLayout
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"
android:orientation="vertical"
android:gravity="center"
android:weightSum=10
android:id="@+id/main">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_pic"
android:layout_weight="2"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2.5"/>
<ImageView
android:id="@+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/btn_click"
android:layout_weight="2"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity implements View.OnTouchListener
{
ImageView img;
private ViewGroup mRrootLayout;
private int _xDelta;
private int _yDelta;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRrootLayout = (ViewGroup) findViewById(R.id.main);
img = (ImageView) mRrootLayout.findViewById(R.id.image);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(300, 300);
img.setLayoutParams(layoutParams);
img.setOnTouchListener(this);
}
修改
public boolean onTouch(View view, MotionEvent event) {
switch (view.getId()) {
case R.id.logo:
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) view.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view
.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
view.setLayoutParams(layoutParams);
break;
}
mRrootLayout.invalidate();
break;
case R.id.fade:
return false;
}
return true;
}
答案 0 :(得分:0)
在onTouch中,您应该检查哪个视图正在被触摸,因此您只知道移动该视图。例如:
public boolean onTouch(View view, MotionEvent event) {
switch (view.getId()) {
case R.id.image:
//Your code goes here
break;
}
return true;
}
这样,只会移动您引用的视图。