Spinner with custom ArrayAdapter for objects not displaying selected item

假如想象 提交于 2019-12-12 10:54:55

问题


I have a custom ArrayAdapter to represent objects on a spinner control, I can load my items list and show it for selection, but when the actual selection happens the spinner shows nothing.

Activity code:

public MetroData metroData;
private Spinner spinner;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    metroData = new MetroData();
    spinner = (Spinner) findViewById(R.id.spinner1);
    StopArrayAdapter dAdapter = new StopArrayAdapter(this, metroData.Stops);

    spinner.setAdapter(dAdapter);
}

StopArrayAdapter:

public class StopArrayAdapter extends ArrayAdapter<MetroStop> {

private List<MetroStop> items;
private Activity activity;

public StopArrayAdapter(Activity activity, List<MetroStop> items) {
    super(activity, android.R.layout.simple_list_item_1, items);
    this.items = items;
    this.activity = activity;
}

@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
    TextView v = (TextView) super.getView(position, convertView, parent);

    if (v == null) {
        v = new TextView(activity);
    }
    v.setTextColor(Color.BLACK);
    v.setText(items.get(position).getName());
    return v;
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;

    if (v == null) {
        LayoutInflater inflater = activity.getLayoutInflater();
        v = inflater.inflate(R.layout.view_spinner_item, null);
    }
    TextView lbl = (TextView) v.findViewById(R.id.text1);
    lbl.setTextColor(Color.BLACK);
    lbl.setText(items.get(position).getName());
    return convertView;
}
}

Spinner view item template:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="#222"/>

Any ideas on why the selected item view doesn't work? Btw, I've also tried it with a normal ArrayAdapter with the same result.

Update Seems that the view gets generated but looking on the hierarchy viewer, the view is not getting rendered, Measured/Layout/Draw = n/a.


回答1:


I found out what was the issue. Since I was fetching the data for the spinner from the internet, I needed to trigger a notifyDataSetChanged(), even though without this the contents of the spinner were updated. It seems that the selected item view didn't get the notice.




回答2:


in getView return convertView; => return v;



来源:https://stackoverflow.com/questions/10678521/spinner-with-custom-arrayadapter-for-objects-not-displaying-selected-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!