0

I am writing an application where need to assign rest of screen space to view.

<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/txtView_1"
            android:layout_width="match_parent"
            android:layout_height="100dp" />

        <TextView
            android:id="@+id/txtView_2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Test Text" />
    </LinearLayout>

and to set runtime I am using following:

private void process() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        int txtView1Height = txtView_1.getHeight();

        LayoutParams layoutParams = (LayoutParams) txtView_2.getLayoutParams();

        layoutParams = new LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                (metrics.heightPixels - txtView1Height));

        txtView_2.setLayoutParams(layoutParams);
    }

But here it's taking not exact same remaining height..since textview sting not placing in center(this is how I simply check)...it might be mistaken to set height in pixel.

Any suggestion here?

CoDe
  • 11,056
  • 14
  • 90
  • 197
  • 2
    No need to do that in code. Just assign `match_parent` to txtView_2's height. It will fill **the remaining space**. – Phantômaxx Jan 05 '15 at 09:08

1 Answers1

3

You can use weight xml parameter

<TextView
android:id="@+id/txtView_2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.0"
android:gravity="center"
android:text="Test Text" />

or in your case simple set height to match_parent

android:layout_height=match_parent

To check even more simpler set gravity to bottom. If you still want to do this programmatically dont use DisplayMetrics to get height (Action Bar and Software Buttons are also a part of display) use your root LinearLayout height. Also check if txtView1Height is not 0 (maybe view was not drawed at the moment of calculation)

Yakiv Mospan
  • 8,174
  • 3
  • 31
  • 35