我有一个AbsoluteLayout
我希望通过我的触摸点移动我的ImageView
这个布局,查看我的代码,当我触摸任何点时,一切都很好,点保存在变量中,但ImageView
消失了,任何想法?
我的XML布局:
<ImageView
android:id="@+id/FirstBall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="59dp"
android:layout_y="446dp"
android:src="@drawable/redball" />
</AbsoluteLayout>
我的代码:
FstBall=(ImageView)findViewById(R.id.FirstBall);
FstBall.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
int action = event.getAction();
float FnlResX = 0;
float FnlResY = 0;
if (action == MotionEvent.ACTION_MOVE){
FnlResX = x;
FnlResY = y;
int tst1 = (int) FnlResX;
int tst2= (int) FnlResY;
FstBall.scrollBy(tst1, tst2);
}
return true;
}
});
答案 0 :(得分:1)
这是一种预期的行为,因为你只是滚动窗口而不是实际移动视图。正确的方法是覆盖布局的onTouchEvent方法。
public class MyAbsoluteLayout extends AbsoluteLayout{
private static final String TAG = MyAbsoluteLayout.class.getSimpleName();
private int mDepth;
@Override
public boolean onTouchEvent(MotionEvent event){
final View child = getChildAt(mDepth);
if(child == null){
Log.e(TAG, "no child at selected depth");
return super.onTouchEvent(event);
}
final ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) child.getLayoutParams();
params.leftMargin = event.getX();
params.topMargin = event.getY();
child.setLayoutParams(params);
return super.onTouchEvent(event);
}
public void setMovingChildDepth(final int depth){
mDepth = depth;
}
}
public class MyActivity extends Activity{
public void onCreate(Bundle data){
super.onCreate(data);
final MyAbsoluteLayout layout = new MyAbsoluteLayout(this);
final ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(FILL_PARENT,FILL_PARENT);
layout.setLayoutParams(layoutParams);
final ImageView imageView = new ImageView(this);
final ViewGroup.MarginLayoutParams viewParams = new ViewGroup.MarginLayoutParams(100,100);
params.leftMargin = 100;
params.topMargin = 100;
imageView.setBackgroundDrawable(yourDrawable);
layout.addView(imageView,params);
layout.setMovingChildDepth(layout.indexOfChild(imageView));
setContentView(layout);
}
}
答案 1 :(得分:0)
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(FstBall.getLayoutParams());
params.x = (int) event.getX();
params.y = (int) event.getY();
FstBall.setLayoutParams(params);
return true;
}