Android 2.1 gridview未显示

时间:2012-07-22 08:12:17

标签: android gridview

我正在尝试在网格视图中显示一些图像。我的代码适用于Android 2.2和2.3,但不适用于2.1

在android 2.1中,网格始终为空/不可见。

我用于网格视图的代码就是这个:

gridview = (GridView)findViewById(R.id.level_select);
gridview.setAdapter(new LevelImagesAdapter(this, levelsCount,
            maxLevel, listener));
gridview.invalidate();

LevelImagesAdapter是:

public class LevelImagesAdapter extends BaseAdapter {

    private View.OnClickListener listener;
    private Context mContext;
    private int count;
    private int maxLevel;

    public LevelImagesAdapter(Context c, int maxLevel, int count, View.OnClickListener listener) {
        this.mContext = c;
        this.listener = listener;
        this.count = count;
        this.maxLevel = maxLevel;
    }

    @Override
    public int getCount() {
        return count;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Button view;
        if (convertView == null) {
            view = new Button(mContext);
            view.setOnClickListener(listener);
            view.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT, GridView.LayoutParams.WRAP_CONTENT));
            view.setPadding(5, 5, 5,5);
        }
        else {
            view = (Button) convertView;
        }

        if (position <= maxLevel) {
            view.setBackgroundResource(R.drawable.level_unlock);
            view.setText((position + 1) + "");
            view.setTextColor(Color.WHITE);
            view.setTextSize(16.0f);
        }
        else {
            view.setBackgroundResource(R.drawable.level_lock);
            view.setText("");
        }
        return view;
    }

}

据我所知,适配器已创建,但从不调用getView方法。

谢谢!

1 个答案:

答案 0 :(得分:6)

您的getItem(position)必须返回NULL

以外的内容

确保getCount()返回非零数字。

检查并确保您的布局中的GridView布局参数设置为fill_parent,而不是match_parent较低的API级别不支持match_parent,因此fill_parent是向后的兼容。可以隐藏GridView,在这种情况下它不会调用getView