0

I want to set the view position in the center of the parent when the button is clicked. How can i do that?

Here is my condition, but when i click the button, the view goes to the upper left corner

    float pHeight = parent.getMeasuredHeight();
    float pWidth = parent.getMeasuredWidth();
   
    button_center.setOnClickListener(v -> {
        textView.setX(pHeight / 2);
        textView.setY(pWidth / 2);
    });
raven-king
  • 1,550
  • 2
  • 18
  • 40
  • Don't get the dimensions of the parent when setting the listener since layout will probably not have happened yet or might still be changed in between and thus the dimension is off (I'd assume in your case height and width are still 0). Instead get the parent dimension inside the listener. That being said you should also consider using a proper layout manager instead of positioning elements yourself. – Thomas Jun 10 '21 at 09:31
  • @camickr do you mean, use LayoutManager instade of Layout? –  Jun 24 '21 at 13:02
  • @HuRa, I deleted that comment. That comment was for Swing. I see now you are not using Swing. Always tag your questions with the toolkit you are using. – camickr Jun 24 '21 at 13:40

0 Answers0