我正在尝试在Views
中动态创建一些LinearLayout
,当创建的视图数较小时,结果看起来像这样的问题:
并且我想让Views
像这样填充所有LinearLayout
:
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);
}
}
}
}
对于您创建的每个视图,似乎都需要为该视图的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);