cjnash cjnash - 1 year ago 52
Android Question

Adjusting the location of an ImageView dynamically based on the location of a Button

I am trying to create an activity that will display an image on the onClick of a button. So far, I have successfully made my application fade the image in when you click the button, but I want the image to be displayed over the button that has been pressed.

From my understanding you want to go about this using

LayoutParams
which I have attempted to do, but it seems to be getting the wrong values from my
Button.getX()
and
getY()
. Here is my code:

button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ConstraintLayout.LayoutParams layoutParamsButton1 = new ConstraintLayout.LayoutParams(((int)button1.getX()), ((int)button1.getY()));
whatImage[0].setLayoutParams(layoutParamsButton1);

fadeInAndHideImage(whatImage[0]);
}
});


whatImage[]
is just an array of
ImageView
s because I want to change their locations around, just fyi.

Anyway, what I think might be happening is a problem with the
getX()
and
getY()
methods retuning wrong values, because my buttons are constrained with
android.support.constraint.Guideline
s. Also, I don't think this is a problem, but I have to cast them as
(int)
s because they both return floats. There might be some rounding errors but I doubt
getX()
and
getY()
would return values that are by the half or quarter pixel.

Thanks

EDIT

Just tried to add
((int)uno.getX()), ((int)firstRail.getY())
into my
LayoutParams
instead of the buttons x and y, (uno and firstRail are guidelines that I use for the button), but it unfortunately put the button in the same exact spot as the
LayoutParams
with the buttons
getX()
and
getY()
methods.

Also, it seems to scale the image down when it moves it, which is also odd

EDIT 2

Ugh, after printing to out to see what exactly these values are,
button1.getX()
and
firstRail.getX()
both return 0.0. Is this even possible while using a Constraint layout??

Answer Source

Try:

whatImage[0].setX(button1.getX() - whatImage[0].getWidth/2);
whatImage[0].setY(button1.gety() - whatImage[0].getHeight/2);

Also keep in mind that resize of image could be happened if you have some padding attribute added to your ImageView into XML

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download