我试图在屏幕上均匀地分布imageviews, imageviews的大小不同,在下面的例子中,我想要有12个imageviews,每一行4个,3行。我得到的问题是,只是聚集在一起的左侧和每次尝试使填充整个行,他们只是拉伸,但我想要一个空间之间的图像视图。我想通过编程来实现,因为我想选择在屏幕上放多少个imageview。我有一个包含linearLayout的布局我想在其中放置imageviews:
<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"
/>
添加imageview的代码在一个片段中:
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);
}
应用程序截图
在布局中创建一个网格视图
Gridview grid = (Gridview) findViewById(R.id.grid_view);
grid.setNumColumns(3);
grid.setColumnWidth(GridView.AUTO_FIT);
grid.setVerticalSpacing(5);
grid.setHorizontalSpacing(5);
grid.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
下面是适配器类:公共类ImageAdapter扩展BaseAdapter {
private Context mContext;
private Bitmap[]mis_fotos;
public ImageAdapter(Context c) {
mContext = c; }
public int getCount() {
return mis_fotos.length;
}
public Object getItem(int position) {
return position; }
public long getItemId(int position) {
return 0; }
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(width/3, height/3));
imageView.setScaleType(ImageView.setScaleType(ScaleType.FIT_XY));
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageBitmap(mis_fotos[position]);
return imageView;
}
}然后将图像列表发送到适配器