简体   繁体   中英

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>

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));

in your LinearLayout, just set

android:layout_height="0dp"
android:layout_weight="1"

As Justin answered

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

You might also need, if you have already set the layout

L.requestLayout();

In Kotlin you can do the following:

L.layoutParams = RelativeLayout.LayoutParams(1080, 400)

And then call L.requestLayout() to apply changes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM