Android:GridView在getView中重置位置

时间:2014-05-31 18:19:02

标签: java android gridview

我用一个阶段列表填充GridView,当前为4.当调用getView(...) 0时,1和2加载正常,显示正确的位置编号。

但是,在位置 3 上,该号码将重置为0,从而为我提供列表:0, 1, 2, 0

public class ExampleGrid extends BaseAdapter{

    private Context mContext;

    public ExampleGrid(Context c){
        mContext = c;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final Button levelButton;    
        if (convertView == null) {
            String positionText = position + "";
            levelButton = new Button(mContext);
            levelButton.setText(mContext.getResources().getString(R.string.mm_stage) + positionText);
            levelButton.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        } else {
            levelButton = (Button) convertView;
        }

        return levelButton;
    }
}

这会打印0, 1, 2, 0。如果我将getCount()方法设置为返回更大的值,则重复该模式。例如:0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, ...

更新:将代码更改为更通用的示例。现在数字首先被加载好了,但是一旦我向下滚动列表,他们就会丢失任何订单。

1 个答案:

答案 0 :(得分:0)

最后通过保留对BaseAdapter中按钮的引用并使用此引用而不是从convertView方法中检查getView(...)来解决此问题。 注意 mButtons

public class ExampleGrid extends BaseAdapter{

    private Context mContext;

    private Button[] mButtons;

    public ExampleGrid(Context c){
        mContext = c;
        mButtons = new Button[getCount()];
    }

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

    @Override
    public Object getItem(int pos) {
        return mButtons[pos];
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final Button levelButton;    
        if (mButtons[position] == null){ 
            String positionText = position + "";
            levelButton = new Button(mContext);
            levelButton.setText(mContext.getResources().getString(R.string.mm_stage) + positionText);
            levelButton.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            mButtons[position] = levelButton;
        } else {
            levelButton = mButtons[position];
        }

        return levelButton;
    }
}