简体   繁体   中英

Spinner Displayed Value (Selection) Changing After Adapter Update (notifyDataSetChanged)

I have a Spinner. After an item is selected, and the adapter is updated by notifyDataSetChanged, the selected item displayed in the Spinner (Textview) changes. This functionality is by design. Because the selected position stayed the same but the value of the selected position changed due to the new content from updating the adapter.

I want to continue to display the originally selected item after the adapter updates.

I was hoping this solution would work, but the event/lister never fires. Maybe because I am using a Spinner and the list is not dispalyed?

https://stackoverflow.com/a/29173680/2330272

mListView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {

  @Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
    mListView.removeOnLayoutChangeListener(this);
    Log.e(TAG, "updated");
  }
});

mAdapter.notifyDataSetChanged();

Update Help with at least two questions:

  1. How to determine when the Spinner has finished updating the view after the notifyDataSetChanged has been called for the adpater?

  2. How to find the position (index) of a value (label) in the adapter? As the adapter be querued or elements loop thru?

If you want to maintain the current selected item , as opposed to the current selected position , then you will have to implement the adapter's getItemId(int position) callback such that:

  • Each item in the spinner has a unique id
  • The same item always has the same id

Common implementations of getItemId() just return zero, or maybe the item's position . Neither of these will work in this situation. Ideally you'll have an actual logical ID that you can return, but if the only thing you have is a String then you could use the string's hashCode() method:

@Override
public String getItem(int position) {
    return list.get(position);
}

@Override
public long getItemId(int position) {
    return list.get(position).hashCode();
}

Two different strings are unlikely to have the same hash code, but it's not impossible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM