以编程方式将重力和重量的视图添加到LinearLayout

时间:2017-01-12 21:40:19

标签: android android-layout

我在xml中生成了LinearLayout,这个:

<LinearLayout
        android:id="@+id/available_themes_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        android:paddingTop="6dp"
        android:paddingBottom="6dp"/>

我正在尝试为此布局添加一些自定义视图,并将它们沿布局均匀放置:

BiColorCircleView lightOrangeCircleView = new BiColorCircleView(getCurrentActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                1.0f);
params.gravity = Gravity.CENTER;
lightOrangeCircleView.setLayoutParams(params);
availableThemesLayout.addView(lightOrangeCircleView);

但最后我实现了只应用了重量并且我的视图与左侧对齐。想一想,如果没有设定重量 - 重力效果很好。

有人能指出我解决这个问题的方法吗?

1 个答案:

答案 0 :(得分:0)

        LinearLayout availableThemesLayout = new LinearLayout(null);
        ImageView lightOrangeCircleView = new ImageView(null);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                1.0f);
        FrameLayout frameLayout = new FrameLayout(null);
        availableThemesLayout.addView(frameLayout, params);

        FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT);
        frameParams.gravity = Gravity.CENTER;
        frameLayout.addView(lightOrangeCircleView, params);

试试这个。