GridView仅显示两列

Bep*_*i's 6 android android-gridview

我以编程方式创建了一个要在Dialog中使用的图像的GridView.如果我将列设置为自动调整,我总是会得到两列,无论图像的大小和屏幕大小如何.如果我将列强制为固定数字,那么它可以正常工作,但我无法避免图像在某些屏幕尺寸上重叠,因此自动管理列数会更好.更重要的是,当我尝试设置拉伸时,它根本没有显示任何东西!

我的ImageAdapter:

public class ImageAdapter extends BaseAdapter {
private Context mContext;

// Constructor
public ImageAdapter(Context c){
    mContext = c;
}

public int getCount() {
    return (IconC.Res.length);
}

public Object getItem(int position) {
    return (IconC.Res[position]);
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) {
        imageView = new ImageView(mContext);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    } else {
        imageView = (ImageView) convertView;
    }
    imageView.setImageResource(IconC.Res[position]);
    return (imageView);
}
 }
Run Code Online (Sandbox Code Playgroud)

以及创建Dialog的函数(在其他地方使用.show()调用)

    private void createPopUp() {
    d_icons = new Dialog(this);
    GridView gv_icons = new GridView(this);

//  gv_icons.setNumColumns(GridView.AUTO_FIT);  // autofit disabled, shows ONLY TWO COLUMNS
    gv_icons.setNumColumns(4); // instead, autofit forced, now it works, but I don't want it fixed!
    gv_icons.setGravity(Gravity.CENTER);
    gv_icons.setHorizontalSpacing(3);
    gv_icons.setVerticalSpacing(1);
//  gv_icons.setStretchMode(GridView.STRETCH_SPACING);  // stretching disabled, shows ZERO COLUMNS
    gv_icons.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    gv_icons.setAdapter(new ImageAdapter(this));
    gv_icons.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
            eventIcons.set(selectedItem, position);
            updateEventView();
            d_icons.dismiss();
        }
    });

    d_icons.setTitle(R.string.text_chooseicon);
    d_icons.addContentView(gv_icons, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    d_icons.setCancelable(true);
}
Run Code Online (Sandbox Code Playgroud)

谁能发现为什么会这样?谢谢!!

以下是4个固定列的显示方式:i50.tinypic.com/2ebdfec.png

以下是自动调整的方法:i50.tinypic.com/25jxo9s.png

以下是在水平选项卡上使用自动调整的布局:i49.tinypic.com/23r7qj5.png

Lev*_*Lev 10

这篇文章回答了你的问题: Android:GridView auto_fit如何找到列数?

为了使auto_fit工作,您需要指定列宽:gridView.setColumnWidth(width);


Roh*_*hit 0

实际上这取决于设备尺寸。当您第一次测试应用程序并固定列数时,网格仅显示 2 列,因为 3 个图像的空间不够大,无法容纳。