【发布时间】:2014-04-02 09:45:57
【问题描述】:
我正在开发一个具有网格视图布局的主屏幕的应用程序。 就目前而言,我在 DP 数字中硬编码盒子的高度和宽度,我显然不想这样做。如何创建代码来确定用户的屏幕尺寸并相应地匹配框,以便拥有大手机(如便笺)的人会看到与 droid mini 上的人相同的东西? IE,当每边硬编码为 500dp 时,它看起来像这样:
但我的目标是让它在每个屏幕尺寸上看起来都像这样:
目前,这是我拥有的 Java 代码:
公共类 ActivityAdapter 扩展 BaseAdapter {
//Array of Icons that will be used as menu choices
public static int[] imageOptions = {
R.drawable.vacation_quota, //Position 0
R.drawable.revenue_deficit, //Position 1
//+ many more options...
};
private Context context;
//Constructor to pass context back to Main class
public ActivityAdapter(Context applicationContext) {
context = applicationContext;
}
//Number of elements to be displayed on the grid
@Override
public int getCount() {
return imageOptions.length;
}
@Override
public View getView(int position, View convertView, ViewGroup arg2) {
ImageView iv;
if(convertView != null){
iv = (ImageView) convertView;
} else {
iv = new ImageView(context);
//Here I have it hard coded to match a 480px width. Here is where I need to change it, just not sure how
iv.setLayoutParams(new GridView.LayoutParams(240, 240));
iv.setScaleType(ScaleType.CENTER_CROP); //Center the cropping
}
//Sets the image to correspond to its position within the array.
iv.setImageResource(imageOptions[position]);
return iv;
}
有什么想法吗?我想从逻辑上讲我想弄清楚屏幕尺寸并使用它们来使图像尺寸匹配,只是不确定如何。其他线程的研究没有太大帮助,所以希望我可以通过代码发布在这里得到一个更简单的答案。
【问题讨论】:
-
只有一种......这里的代码无法正常工作,因为我无法在活动类之外完成这项工作,并且我试图避免改变应用程序的基本结构。我最终只提出了一个简单的建议:iv = new ImageView(context); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);显示显示 = wm.getDefaultDisplay();浮动宽度2 = display.getWidth(); int 长度 = (int) (width2/2); iv.setLayoutParams(new GridView.LayoutParams(length, length));
标签: android gridview grid imageview baseadapter