Search code examples
javaandroidandroid-wrap-content

setting height to wrap_content in Java makes the view deny all predefined XML attributes?


I have created a TextView in XML and have set some rules for it (for example layout_bellow="something"), and made it's height set to 0, so that when a button is clicked, it's height would be set to wrap_content. I wrote the code bellow for the button responsible for resizing, and below it is the XML code i wrote for the TextView. The problem is, when i click the button, the height becomes match_parent, the layout_bellow attribute gets ignored and it is drawn from the start of the parent layout, and width (that was set to match_parent) becomes wrap_content. Whats the problem? thanks.

the Button:

    btnExpand.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            textView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, height));
        }
    });

the XML:

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:id="@+id/firstRow"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                .
                .
                .
            </LinearLayout>

            <TextView
                android:id="@+id/theTextView"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_below="@id/firstRow"
                android:text="lorem ipsom lorem ipsom">

        </RelativeLayout>

EDIT: here's an image to demonstrate the problem


Solution

  • Basically the problem is you are creating new LayoutParams and setting it to the view. You have get the already set(xml) LayoutParams of the view and modify whichever you want to modify and set it back to the View.

    LayoutParams layoutParams = textView.getLayoutParams();
    //height = LayoutParams.WRAP_CONTENT;or 100 or whatever
    layoutParams.height = LayoutParams.WRAP_CONTENT;
    textView.setLayoutParams(layoutParams);