LinearLayout setMargins以编程方式生效

时间:2015-10-07 11:34:44

标签: android android-linearlayout programmatically-created

请查看以下代码:

        LinearLayout ll1 = new LinearLayout(context);
        ll1.setBackgroundColor(Color.BLUE);
        ll1.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams ll1LayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        ll1LayoutParams.setMargins(100, 0, 100, 0);
        ll1.setLayoutParams(ll1LayoutParams);
        ...
        // parentLayout is FrameLayout
        parentLayout.addView(ll1, ll1LayoutParams);

为什么它不起作用?

1 个答案:

答案 0 :(得分:2)

更改

LinearLayout.LayoutParams ll1LayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

FrameLayout.LayoutParams ll1LayoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

将布局参数分配给子项时,必须指定其父项的LayoutParams类,而不是视图。由于您的父视图是FrameLayout,因此您必须使用FrameLayout.LayoutParams。