Spinner with custom ArrayAdapter for objects not d

2019-06-22 05:56发布

问题:

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;