1

I want to translate relative layout in vertical axis by %50 percentage of its height. How to do it?

<RelativeLayout
    android:id="@+id/rl"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:translationY="50dp"> <!-- i tried 50% , .50. But it does not work.

Then i tried to find its height in onCreate of the activity, then translate dynamically %50 percentage. but height returns zero.

onCreate(){
     ...
     RelativeLayout rl = findViewById(R.id.RL);
     rl.getHeight();
}

How to do it?

metis
  • 1,024
  • 2
  • 10
  • 26
  • In onCreate you cannot retrieve the height of layouts, I don't remember why, but it something related to the view not drawn yet or something like this – Chol May 04 '18 at 08:46
  • Used linear layout to provide divided UI into a percentage. –  May 04 '18 at 08:47
  • check here to get the height: https://stackoverflow.com/questions/7733813/how-can-you-tell-when-a-layout-has-been-drawn – Chol May 04 '18 at 08:47
  • Possible duplicate of [getWidth() returns 0 in onCreate](https://stackoverflow.com/questions/26221081/getwidth-returns-0-in-oncreate) – Suleyman May 04 '18 at 08:47
  • Try `weight`. You can divide the screen with required % for each layout using this. – Sunil Sunny May 04 '18 at 09:01
  • As mentioned above, the simplest way to do is to use LinearLayout and weight property for percentage. – Kunu May 04 '18 at 09:55

2 Answers2

1

You cannot retrieve height of a view in onCreate(). Because it is not measured and drawn yet. Try this:

RelativeLayout rl = findViewById(R.id.RL);
    rl.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                public void onGlobalLayout() {
                    rl.getMeasuredHeight();
                }
            });

After you get the height, you can use it as you wish for translation.

anzaidemirzoi
  • 386
  • 4
  • 13
-1

Android has some annoying bugs that make us use useless hacks. For getting the height in onCreate i used this:

    var handler=Handler()
    handler.postDelayed(object:Runnable{
        override fun run() {
            findViewById<RelativeLayout>(R.id.toMove).y=findViewById<RelativeLayout>(R.id.toMove).y+(findViewById<RelativeLayout>(R.id.toMove).height/2)
        }
    }, 200)

I know it is a delay of 200 mills and t is not the best solution but it is easy to implement and works just fine.

Alexandru Sandu
  • 314
  • 2
  • 13