Как сделать, чтобы Представления заполняли весь размер LinearLayout - PullRequest
0 голосов
/ 17 октября 2019

Я пытаюсь создать некоторые Views динамически в LinearLayout, проблема, когда количество созданных представлений мало, результат выглядит следующим образом:

enter image description here

И я хочу, чтобы Views заполнил все LinearLayout следующим образом:

enter image description here

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);
                }
        }

    }
}

1 Ответ

0 голосов
/ 18 октября 2019

Для каждого из созданных вами представлений, похоже, вам нужно будет присвоить вес параметрам 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);
...