【问题标题】:How to make Views fill all LinearLayout size如何使视图填充所有 LinearLayout 大小
【发布时间】:2020-02-14 18:35:38
【问题描述】:

我正在尝试在LinearLayout 中动态创建一些Views,当创建的视图数量很少时,结果如下所示:

我想让Views 像这样填充所有LinearLayout

线性布局 XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/palette_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" />
</LinearLayout>

查看 XML:

<View xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:layout_weight="1" />

Java:

 public class ColorPaletteResultsFragment extends Fragment {
    public ColorPaletteResultsFragment() {
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_palette_results, container, false);
        configure(view);
        return view;
    }

    private void configure(View view) {
        LinearLayout palletContainer = (LinearLayout) view.findViewById(R.id.palette_container);
        fillPalletColors(mPalette, palletContainer);
    }

    private void fillPalletColors(List<Integer> colors, LinearLayout paletteContainer) {
        if (getActivity() != null && isAdded()) {
            LayoutInflater inflater = getActivity().getLayoutInflater();
             for (int color : colors) {
                    View palletColor = inflater.inflate(R.layout.suggested_color_item, paletteContainer, false);
                    palletColor.setBackgroundColor(color);
                    paletteContainer.addView(palletColor);
                }
        }

    }
}

【问题讨论】:

  • 我测试了您的代码,它对我来说运行良好。您是否在任何地方更改布局参数?调色板容器是对调色板容器的引用吗?我认为您可能需要分享更多信息/代码
  • @W0rmH0le 非常感谢您的帮助,我已经用更多代码更新了我的问题

标签: android xml view android-linearlayout


【解决方案1】:

对于您创建的每个视图,您似乎需要为该视图的 LinearLayout.LayoutParams 参数分配权重。

权重为 1/n,其中 n 是观看次数。

int viewCount = 6;
View view = new View(getContext());
            float weight = 1/viewCount;
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,weight);
            view.setLayoutParams(params);

【讨论】:

    猜你喜欢
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多