关于GridView上适配器的设计问题

时间:2011-06-01 05:26:14

标签: android

你有一个带有我自己的Adapter类的GridView。此GridView将TextViews显示为其项目(简化):

@Override
public View getView(int arg0, View convertView, ViewGroup arg2) {           

    final LinearLayout linearLayout;          

    if (convertView == null) {  // if it's not recycled, initialize some attributes

        LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        linearLayout = (LinearLayout)inflater.inflate(R.layout.settings_timer_textview, null);
        TextView textView = (TextView)linearLayout.findViewById(R.id.timer_textview);
        textView.setText(text);     

    } else {
        linearLayout = (LinearLayout) convertView;
    }        

    return linearLayout;

}

我的TextView项目及其文本的数量在运行时可能会如何变化。这意味着,也许起初我的GridView中有12个TextView,但是通过另一个活动中的用户配置,当用户返回到GridView活动时,只剩下10个TextView。我如何实现这样的更新?如果我只调用notifyDataChanged()然后调用getView但是linearLayout!= null,因此文本将不会更新(请参阅上面的代码 - else分支)。有任何想法吗?感谢。

1 个答案:

答案 0 :(得分:0)

您只需要将文本更新代码移出if语句:

@Override
public View getView(int arg0, View convertView, ViewGroup arg2) {           

    final LinearLayout linearLayout;          

    if (convertView == null) {  // if it's not recycled, initialize some attributes

        LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        linearLayout = (LinearLayout)inflater.inflate(R.layout.settings_timer_textview, null);   
    } else {

        linearLayout = (LinearLayout) convertView;
    }

    TextView textView = (TextView)linearLayout.findViewById(R.id.timer_textview);
    textView.setText(text);  

    return linearLayout;

}