如何在GridView中根据屏幕大小设置图像的宽度和高度

13

我想展示一个3x3的网格视图。我想根据设备尺寸设置高度和宽度。我正在参考这个链接

MainActivity-

public class MainActivity extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      GridView gridview = (GridView) findViewById(R.id.gridview);
      gridview.setAdapter(new ImageAdapter(this));
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

}

主活动-

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
   android:id="@+id/gridview"
   android:layout_width="fill_parent" 
   android:layout_height="fill_parent"
   android:columnWidth="90dp"
   android:numColumns="auto_fit"
   android:verticalSpacing="10dp"
   android:horizontalSpacing="10dp"
   android:stretchMode="columnWidth"
   android:gravity="center"
/>

编辑 -

就像首先获取屏幕的高度和宽度,然后每个项目的高度和宽度都是屏幕高度和宽度值的1/3一样。


这里你的列固定为3。 - M D
我知道,但在某些屏幕上,网格视图中的图像仅占据了屏幕的一半以上。 - John R
在你的代码中设置宽度,获取屏幕宽度并将其设置为 gridView 的宽度的三分之一。 - Shayan Pourvatan
如何获取屏幕宽度以及在哪里设置? - John R
你想要显示一个固定的3x3网格(9个项目恒定)还是一个3x3格式的网格(可滚动)并且项目数量不确定? - alex
显示剩余2条评论
3个回答

9

不要使用屏幕尺寸,在多窗口情况下,这种方法是无效的。 如果你的网格是一个3x3的项目,大小固定,那么请使用自定义布局ViewGroup,如下所示:(并设置RelativeLayout项目内容)

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle state) {
        setContentView(new ViewGroup(this) {
            private RelativeLayout[] items = new RelativeLayout[9];
            private int width, height, itemWidth, itemHeight;
            {
                Random r = new Random();
                for (int i = 0; i < 9; i++) {
                    items[i] = new RelativeLayout(getContext());
                    float[] hsv = new float[] {360 * r.nextFloat(), .50f, .75f};
                    items[i].setBackgroundColor(Color.HSVToColor(hsv));
                    addView(items[i]);

                    // UPDATE ////////////////////////////////////
                    ImageView image = new ImageView(getContext());
                    switch (i) {
                    case 0: // top left
                    case 1: // top center
                    case 2: // top right
                    case 3: // center left
                    case 4: // center center
                    case 5: // center right
                    case 6: // bottom left
                    case 7: // bottom center
                    case 8: // bottom right
                        image.setImageResource(R.drawable.ic_launcher);
                        break;
                    }
                    image.setScaleType(ScaleType.FIT_XY);
                    image.setLayoutParams(new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.MATCH_PARENT,
                            RelativeLayout.LayoutParams.MATCH_PARENT
                    ));
                    items[i].addView(image);
                    //////////////////////////////////////////////
                }
            }
            @Override
            protected void onMeasure(int wMS, int hMS) {
                width = MeasureSpec.getSize(wMS);
                height = MeasureSpec.getSize(hMS);
                itemWidth = width / 3;
                itemHeight = height / 3;
                wMS = MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY);
                hMS = MeasureSpec.makeMeasureSpec(itemHeight, MeasureSpec.EXACTLY);
                measureChildren(wMS, hMS);
                setMeasuredDimension(width, height);
            }
            @Override
            protected void onLayout(boolean changed, int l, int t, int r, int b) {
                for (int i = 0; i < 9; i++) {
                    l = itemWidth * (i % 3);
                    t = itemHeight * (i / 3);
                    r = l + itemWidth;
                    b = t + itemHeight;
                    items[i].layout(l, t, r, b);
                }
            }
        });
        super.onCreate(state);
    }

}

编辑:请看我的代码更新,你只需将图片添加到项目容器中即可。使用这种方法,不需要XML布局文件,因为你自己管理内容和大小。

结果result


编辑:极简主义方式:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle state) {
        setContentView(new ViewGroup(this) {
            private static final int SIZE_X = 3;
            private static final int SIZE_Y = 3;
            private ImageView[] items = new ImageView[SIZE_X * SIZE_Y];
            private int itemWidth, itemHeight;
            {
                setBackgroundColor(Color.DKGRAY);
                for (int i = 0; i < items.length; i++) {
                    items[i] = new ImageView(getContext());
                    items[i].setScaleType(ScaleType.CENTER);
                    items[i].setImageResource(R.drawable.ic_launcher);
                    addView(items[i]);
                }
            }
            @Override
            protected void onMeasure(int wMS, int hMS) {
                int width = MeasureSpec.getSize(wMS);
                int height = MeasureSpec.getSize(hMS);
                itemWidth = width / SIZE_X;
                itemHeight = height / SIZE_Y;
                wMS = MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY);
                hMS = MeasureSpec.makeMeasureSpec(itemHeight, MeasureSpec.EXACTLY);
                measureChildren(wMS, hMS);
                setMeasuredDimension(width, height);
            }
            @Override
            protected void onLayout(boolean changed, int l, int t, int r, int b) {
                for (int i = 0; i < items.length; i++) {
                    l = itemWidth * (i % SIZE_X);
                    t = itemHeight * (i / SIZE_X);
                    r = l + itemWidth;
                    b = t + itemHeight;
                    items[i].layout(l, t, r, b);
                }
            }
        });
        super.onCreate(state);
    }

}
结果

enter image description here


@Kanwaljit Singh:

在MainActivity中的项目创建循环中:

final int id = i;
items[i].setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        startActivity(new Intent(getContext(), NextActivity.class).putExtra("id", id));
    }
});

在NextActivity中:

int id = getIntent().getIntExtra("id", -1);

只需将此代码复制粘贴到您的项目中,并根据您的需求进行调整。 - alex
你完全改变了我的代码。如果我必须把图像的值发送到下一个活动,请帮帮我。例如,第一张图片点击后将0发送到下一个活动。 - Kanwaljit Singh
@alex,它正在工作。最后一个问题是如何在行和列中设置垂直和水平填充? - John R
@JohnR 如果它可以工作,你可以批准Alex的答案吗? :-) - Jagadeesh
@Jagadeesh 当然。但在得到我上一个问题的答案之后。 - John R
显示剩余5条评论

4

您可以通过以下方式获取屏幕尺寸:

final DisplayMetrics displayMetrics=getResources().getDisplayMetrics();
final float screenWidthInDp=displayMetrics.widthPixels;
Log.WTF("ScreenWidth", "width: "+screenWidthInDp+", menuWidth: "+screenWidthInDp/3);

对于gridview,我建议您查看这个很棒的库,名为Staggered Grid View。他们的示例在这里。


我不想使用交错网格视图。如果我使用你建议的上述代码,那么以上代码需要做出哪些改变? - John R
不,情况并非如此。我在模拟器上尝试了这段代码。 - John R

2

当我需要调整Activity大小时,我使用以下方法,我认为对于您的情况也是有效的:

// I'm storing the size of the window in the display var, so I can then play around
final Display display = getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize(size);

// In your case, you'll probably need something like this:
GridView gv = (GridView) findViewById(R.id.gridview);
gv.setWidth((int) size.x * 0.75);    // Whis would resize the grid width to the 75%
gv.setHeight((int) size.y * 0.5);    // Same with the height, but to the 50%

我已经为您删除了无用的行。在您的情况下,只需将这6行放入您的代码中,在填充GridView之前,但是您需要通过它们的ID找到它们(我的意思是,一旦布局已呈现),只需更改%以调整大小所需的大小即可。它应该可以正常工作。 - nKn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接