Android - GridView 强制更新数据更改

Android - GridView forcing update on data change

我已经实现了这个示例(2.自定义适配器示例) http://www.mkyong.com/android/android-gridview-example/ 并且有效。

然后我想 "refresh" 使用一组新数据,直到我这样做才起作用:

imageAdapter.notifyDataSetChanged();

然后删除了 ImageAdapter getView 方法中的以下检查:

 if (convertView == null) {

这是我当前的 getView 方法

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

    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View gridView;

    // if (convertView == null) {  // stopped my GridView from updating !!
    if (true)
    {
        gridView = new View(context);

        // get layout from mobile.xml
        gridView = inflater.inflate(R.layout.mobile, null);

        // set value into textview
        TextView textView = (TextView) gridView
                .findViewById(R.id.grid_item_label);

        textView.setText(mobileValues[position]);


        // set image based on selected text
        ImageView imageView = (ImageView) gridView
                .findViewById(R.id.grid_item_image);

        imageView.setImageResource(R.drawable.square);


    } else {
        gridView = (View) convertView;
    }

    return gridView;
}

我担心它现在一遍又一遍地进行不必要的处理 - 即多次膨胀视图?

我应该在每次调用时创建一个新的 GridView 吗?

它不起作用,因为以下行

   TextView textView = (TextView) gridView
            .findViewById(R.id.grid_item_label);

    textView.setText(mobileValues[position]);


    // set image based on selected text
    ImageView imageView = (ImageView) gridView
            .findViewById(R.id.grid_item_image);

    imageView.setImageResource(R.drawable.square);

到 if/else 外面去。检查 if (convertView == null) 是必要的。如果你没有它,你会膨胀 n 个不同的视图,n == getCount()。对于 n 大,这将是一个问题。您可能希望实施 android ViewHolder 模式,为您的用户提供最佳的用户体验。

正如@Vzsg 正确指出的那样,也去掉了 gridView = new View(context);。这是一个额外的无用分配

我通常只用新结果更新适配器,然后将其设置到 GridView。

因此在您的示例中,当我想更新我的 GridView 时 - 我执行以下操作。

gridView.setAdapter(newAdapter);

你可以有一个实用的方法,这样可以更容易地获得一个新的适配器。

private ArrayAdapter getAdapter(String [] data){...}