问题
I'm coding with API 8.
I need to get coordinates X and Y from a View and and set them as the coordinates of a new Button.
I tried different ways but nothing works....
The setX and getX method works only from api level 11, I need a way to do that on API8.
This is my method that allow to create a draggable copy of a button (this copy is an imageview and when I drop it became a new button)
public boolean dragCopy(View view, MotionEvent me, Button bt){
int x,y,w,h,id,t,l;
int cont=-1;
int coord[] = new int[2];
bt2=new Button(this);
id = bt.getId();
bt2.setId(id);
Resources res = getResources();
cont = FindCont(bt, vector);
dr = getLetter(bt, dr, res, vector, cont);
w=dr.getIntrinsicWidth();
h=dr.getIntrinsicHeight();
if (me.getAction() == MotionEvent.ACTION_DOWN) {
//clicked on the button. DRAG START
status = START_DRAGGING;
image = new ImageView(this);
//set image drawable
image.setImageDrawable(dr);
image.setPadding((int)bt.getLeft(),(int)bt.getTop(), 0, 0);
layout.addView(image, params);
}
if (me.getAction() == MotionEvent.ACTION_UP) {
//button released. DROP
status = STOP_DRAGGING;
x = (int) me.getRawX();
y = (int) me.getRawY();
//create button compy from image
bt2.setBackgroundDrawable(dr);
bt2.setVisibility(View.VISIBLE);
//PROBLEMS
t= image.getTop();
l= image.getLeft();
bt2.setPadding(l, t, 0, 0);
System.out.println("**************** T: "+t +"--- L: "+l);
image.setVisibility(View.GONE);
bt2.setLayoutParams(image.getLayoutParams());
bt2.setWidth(w);
bt2.setHeight(h);
layout.addView(bt2);
bt2.setDrawingCacheEnabled(true);
bt2.setOnTouchListener(this);
bt2.invalidate();
image.invalidate();
} else if (me.getAction() == MotionEvent.ACTION_MOVE) {
//i'm moving the image
if (status == START_DRAGGING) {
image.setPadding((int) me.getRawX(), (int) me.getRawY(), 0, 0);
image.invalidate();
}
}
return false;
}
回答1:
you could try getTop() and getLeft()?
回答2:
I haven't tried this, but I think it will work:
int buttonX = 50; // Arbitrary values - use whatever you want
int buttonY = 100;
int viewX = myView.getLeft();
int viewY = myView.getTop();
Button newButton = new Button();
newButton.setPadding(buttonX - viewX, buttonY - viewY, 0, 0);
// Other button setup
That will set it to an absolute position of (50,100) on the screen. If you want it to be (50,100) relative to the corner of your layout then use this:
int buttonX = 50; // Arbitrary values - use whatever you want
int buttonY = 100;
Button newButton = new Button();
newButton.setPadding(buttonX, buttonY, 0, 0);
// Other button setup
This will only work on layouts that don't automatically position their child content, such as RelativeLayout.
回答3:
i've recreate my drag and drop using andengine. Works great and better than before
来源:https://stackoverflow.com/questions/7869604/android-api-8-get-x-and-y-from-a-view-and-set-x-and-y-on-a-button