更新自定义ListView项目

时间:2010-12-24 18:20:13

标签: java android

我有一个listview,它使用基于baseadapter的customadapter。列表视图使用外部数据填充,我可以选择点击事件并知道选择了哪个项目。

我在更新点击项目的视图时遇到问题,例如TextView和ViewFlipper。

我是否必须通过列表视图更新内容或是通过适配器更新。我尝试了类似下面的内容;​​

View test = (View)adapter.getView(pos, null, myListView);
ViewFlipper temp = (ViewFlipper)test.findViewById(R.id.flipholder);
temp.showNext();
TextView temp2 = (TextView)test.findViewById(R.id.filmtitle);
temp2.setText("Hello World");

这会导致viewfliper翻转第一个和第三个项目或第二个和第四个项目,而文本根本不会更新。

有什么想法吗?

干杯

1 个答案:

答案 0 :(得分:1)

在getView中尝试此模式:

public View getView(int position, View convertView, ViewGroup parent) {
        // A ViewHolder keeps references to children views to avoid unneccessary calls
        // to findViewById() on each row.
        ViewHolder holder;

        // When convertView is not null, we can reuse it directly, there is no need
        // to reinflate it. We only inflate a new View when the convertView supplied
        // by ListView is null.
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item_icon_text, null);

            // Creates a ViewHolder and store references to the two children views
            // we want to bind data to.
            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.text);
            holder.icon = (ImageView) convertView.findViewById(R.id.icon);

            convertView.setTag(holder);
        } else {
            // Get the ViewHolder back to get fast access to the TextView
            // and the ImageView.
            holder = (ViewHolder) convertView.getTag();
        }

        // Bind the data efficiently with the holder.
        holder.text.setText(DATA[position]);
        holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);

        return convertView;
    }

    static class ViewHolder {
        TextView text;
        ImageView icon;
    }
}