如何动态调整android布局的大小

时间:2010-09-01 15:09:23

标签: android

我需要根据从配置文件加载的信息动态(以编程方式)调整应用程序的最顶层布局。

现在我在main.xml中有

 <?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout   
            android:id="@+id/LinearLayout01" 
            android:layout_width="fill_parent" 
            android:layout_height="fill_parent" 
            xmlns:android="http://schemas.android.com/apk/res/android" 
            android:background="@drawable/background">
    </LinearLayout>

所以我正在寻找一种以编程方式更改android:layout_width和layout_height的方法。

任何帮助将不胜感激

RM

编辑:

根据建议,我尝试了以下内容:

LinearLayout l2 = (LinearLayout)findViewById(R.id.LinearLayout07);
LinearLayout.LayoutParams params =  new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT,1);
l2.setLayoutParams(params);

但是在运行时会出现以下错误:

Thread [<3> main] (Suspended (exception ClassCastException))    
FrameLayout.onLayout(boolean, int, int, int, int) line: 288 
FrameLayout(View).layout(int, int, int, int) line: 6133 
....

2 个答案:

答案 0 :(得分:3)

LinearLayout.LayoutParams params =
                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT,1);


layout.setLayoutParams(params);

布局是使用findViewById获取的LinearLayout。在我的示例中,宽度和高度的参数是fill_parent,权重为1。

当然,您可以使用固定大小(以像素为单位)代替fill_parent选项,或者如果您不想要它,则省略重量。

答案 1 :(得分:0)

当您尝试获取LinearLayout时,我发现了一个错误。您将其写为LinearLayout07而不是LinearLayout01