如何在java代码中使用wrap_cotent创建LinearLayout?

时间:2012-04-11 00:03:46

标签: java android android-layout

java在编程上等效于创建以下XML文件的内容:

<LinearLayout
   android:layout_width="wrap_content"
   android:layout_height="wrap_content">
     <RelativeLayout />
</LinearLayout>

我尝试这样做,但有些LinearLayout如何延伸至MATCH_PARENT

// child is the RelativeLayout in the above example:
LinearLayout parent = new LinearLayout(getContext());
LinearLayout.LayoutParams childLayoutParams = new LinearLayout.LayoutParams(
  LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
parent.addView(child, -1, childLayoutParams);

2 个答案:

答案 0 :(得分:1)

试试这个

LinearLayout parent = new LinearLayout(getContext());
LayoutParams parentLayoutParams = new LinearLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
parent.setLayoutParams(parentLayoutParams);

然后将其添加到屏幕

outerlayout.addView(parent);

答案 1 :(得分:0)

您设置的LayoutParams适用于RelativeLayout,不适用于LinearLayout。我会打赌,LinearLayout使用MATCH_PARENT作为默认参数。当您将parent添加到Window或root ViewGroup时,您应该创建一组正确的LayoutParams并指定WRAP_CONTENT