CoDe
CoDe

Reputation: 11156

set remaining height to view at runtime

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?

Upvotes: 0

Views: 527

Answers (1)

Yakiv Mospan
Yakiv Mospan

Reputation: 8224

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)

Upvotes: 3

Related Questions