我尝试使用像Image1这样的网格视图制作带有4个图像的主菜单活动。但是图像不占据活动的整个空间。 Image2显示了我的网格视图。如何在不滚动的情况下对齐4个图像并适合所有屏幕,如Image1?
activity_main_menu.xml
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="2"
tools:context=".MainMenuActivity"
/>
MainMenuActivity.java
public class MainMenuActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
}
}
ImageAdapter.java
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView ;
if(convertView==null)
{
imageView = new ImageView(mcontext);
WindowManager wm = (WindowManager) mcontext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);
float density = mcontext.getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth = outMetrics.widthPixels / density;
int width=(int) (dpWidth/2);
int height=(int) (dpHeight/2);
imageView.setLayoutParams(new GridView.LayoutParams(parent.getWidth()/2,parent.getHeight()/2));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//imageView.setLayoutParams(new GridView.LayoutParams(width,height));
//imageView.setLayoutParams(new GridView.LayoutParams(imageView.getWidth(),imageView.getHeight()));
//imageView.setBackgroundColor(000000);
//imageView.setLayoutParams(new GridView.LayoutParams(400,200));
//imageView.setLayoutParams(new GridView.LayoutParams());
//imageView.setPadding(40,40,40,40);
}
else
{
imageView=(ImageView)convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.mainmenu1, R.drawable.mainmenu2,
R.drawable.mainmenu3, R.drawable.mainmenu4
};
答案 0 :(得分:1)
您需要指定一个单独的布局来表示gridview中的每个项目。最有可能的情况是,如果您尝试模拟图像1,则必须创建一个单独的布局,其中RelativeLayout作为父级,ImageView和TextView作为子级。设置imageview的高度和宽度以匹配parent(带有一些填充),并将TextView放在图像的顶部。
您还必须修改适配器以扩充此自定义视图并将数据源绑定到它(图像和文本)。
答案 1 :(得分:1)
在您的代码中执行此操作:
float density = mcontext.getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth = outMetrics.widthPixels / density;
int width=(int) (dpWidth);
int height=(int) (dpHeight);
imageView.setLayoutParams(new GridView.LayoutParams(width,height));
imageView.setBackgroundColor(000000);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
它将删除所有间距黑白图像。你可以禁用gridview上的滚动。