我遇到了一个奇怪的错误,当这个代码作为一个应用程序运行时,灰色框被拖放到左边一点点,我再也不能将它拖到屏幕的左边四分之一。
这是我的代码......
import android.graphics.Point;
import android.os.Bundle;
import android.app.Activity;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class drag_activity extends Activity implements View.OnTouchListener{
private ViewGroup viewGroup;
private ImageView imageBackground;
private int xPos;
private int yPos;
int width;
int height;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drag_activity);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
viewGroup = (ViewGroup) findViewById(R.id.marco);
imageBackground = (ImageView)findViewById(R.id.imageView);
findViewById(R.id.imageView3).setOnTouchListener(this);
findViewById(R.id.imageView4).setOnTouchListener(this);
findViewById(R.id.imageView5).setOnTouchListener(this);
findViewById(R.id.imageView6).setOnTouchListener(this);
findViewById(R.id.imageView7).setOnTouchListener(this);
findViewById(R.id.imageView8).setOnTouchListener(this);
findViewById(R.id.imageView10).setOnTouchListener(this);
findViewById(R.id.imageView11).setOnTouchListener(this);
findViewById(R.id.imageView12).setOnTouchListener(this);
findViewById(R.id.imageView13).setOnTouchListener(this);
width = size.x;
height = size.y;
View.OnTouchListener clickListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
Toast.makeText(drag_activity.this, "Max Walls reached!", Toast.LENGTH_LONG).show();
return false;
}
};
imageBackground.setOnTouchListener(clickListener);
}
public boolean onTouch(View view, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams Params = (RelativeLayout.LayoutParams) view.getLayoutParams();
xPos = X - Params.leftMargin;
yPos = Y - Params.topMargin;
break;
case MotionEvent.ACTION_UP:
Toast.makeText(this,""+view.getY(),Toast.LENGTH_SHORT).show();
if(view.getY() > height-(120 + imageBackground.getHeight())){
view.setY(height-(20+imageBackground.getHeight()));
view.setX((width/2)-(imageBackground.getWidth()/2));
}
Toast.makeText(this,""+view.getY(),Toast.LENGTH_SHORT).show();
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
layoutParams.leftMargin = X - xPos;
layoutParams.topMargin = Y - yPos;
layoutParams.rightMargin = -50;
layoutParams.bottomMargin = -50;
view.setLayoutParams(layoutParams);
break;
}
viewGroup.invalidate();
return true;
}}
任何解释或建议都会有所帮助,谢谢!
这是一张图片: