开发者

How to get a View from an Android Adapter from an Item

Given an Item which is displayed in a ListView,

Can I use its Adapter (or the ListView itself) to find the View which displays the Item?

I am handling the saving of Item data and must propagate the change back to the ListView. Adding an item makes it show up using notifyDataSetChanged() but the changed items are not redrawn using notifyDataSetChanged()

Here is the code for my activity which edits the item:

@Override
public void onClick(View button) {
    EditText text = (EditText)(findViewById(R.id.itemText));
    if (item == null) {
       // Add - this path updates ListView
       ItemsAdapter.instance().items.add(new Item(text.getText().toString()));
    } else {
       // Save - this path does not update ListView
       this.item.setTitle(text.getText().toString());
    }
    ItemsAdapter.instance().notifyDataSetChanged();
    this.finish(); // Close activity
}

The relevant parts of my adapter are:

public class ItemsAdapter extends BaseAdapter {
    ArrayList<Item> items = new ArrayList<Item>();

    @Override
开发者_开发问答    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Item item = (Item)getItem(position);
        // ItemTextView is a subclass of TextView which keeps a reference to the item
        // So that in my OnClickListener, I can get the underlying Item and edit it
        ItemTextView textView = null;
        if (convertView == null) {
            textView = new ItemTextView(context, item);
            // Associate with itemListener which opens edit activity for item
            textView.setOnClickListener(itemListener);
            textView.setTextSize(16);
            textView.setPadding(5, 5, 5, 5);
        } else {
            textView = (ItemTextView) convertView;
            textView.setItem(item);
        }

        return textView;
    }
}

And the Item class is a POJO which implements Parcelable.

Thanks In Advance

jeff


Ok, I was wrong and adamp was right.

The problem was a newbie one. I was updating the Item I got from a bundle in the child activity. When control passed back to the original activity, the original activity was unchangwd.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜