Search code examples
androidandroid-layoutandroid-linearlayout

dynamically set LinearLayout height/width in relativelayout


i have a linearLayout inside a RelativeLayout. I need to be able to set the height of the linearlayout dynamically depending on the screen dimensions. Im having some difficulties. how can i achieve this?

MAIN :

 public class MainActivity extends Activity {

LinearLayout L;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    L=(LinearLayout)findViewById(R.id.top);

    L.setLayoutParams(new LinearLayout.LayoutParams(1080, 400));
}

}

XML:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"

 tools:context=".MainActivity" >

 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#fff"
    android:id="@+id/top"
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
</LinearLayout>


Solution

  • When you set layout params, it needs to be that of the parent.

    Switch:

    L.setLayoutParams(new LinearLayout.LayoutParams(1080, 400));
    

    To:

    L.setLayoutParams(new RelativeLayout.LayoutParams(1080, 400));