我试图在屏幕上均匀分布图像视图,图像视图大小不同,在下面的示例中,我希望有 12 个图像视图,每行 4 个和 3 行。我得到的问题是,只是聚集在左边,每次尝试填充它们只是伸展的整行,但我想要在图像视图之间留一个空间。我想以编程方式执行此操作,因为我想选择在屏幕中放置多少图像视图。我有一个布局,它只包含一个线性布局,我想在其中放置图像视图:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/treasureLinearLayout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff134BE8"
android:padding="10dp"
/>
添加图像视图的代码位于片段中:
final float scale = getContext().getResources().getDisplayMetrics().density;
int dps = 90;
LinearLayout layout = (LinearLayout) view.findViewById(R.id.treasureLinearLayout);
layout.setOrientation(LinearLayout.VERTICAL); //Can also be done in xml by android:orientation="vertical"
for (int i = 0; i < 3; i++) {
LinearLayout row = new LinearLayout(getContext());
row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f);
row.setLayoutParams(param);
for (int j = 0; j < 4; j++) {
dps -= 5;
ImageView imageView = new ImageView(getContext());
imageView.setImageResource(R.drawable.ic_menu_map);
imageView.setBackgroundResource(R.drawable.circle);
imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
int pixels = (int) (dps * scale + 0.5f);
imageView.getLayoutParams().height = pixels;
imageView.getLayoutParams().width = pixels;
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
row.addView(imageView);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TreasuresFragment treasureFrag = ((NavigationDrawerActivity) getActivity()).getTreasureFrag();
((NavigationDrawerActivity)getActivity()).showHideFragment(treasureFrag);
}
});
}
layout.addView(row);
}