如何在可搜索的微调器中更改项目的文本

时间:2017-02-03 07:51:39

标签: android android-arrayadapter android-spinner

我正在尝试创建一个可搜索的微调器并将数组适配器连接到它。微调器的内容应该是一个对象(我这样做,所以我可以检索id并显示名称)。我差不多完成但是没有显示的名字,我得到了这个: searchable spinner

这是我的代码:

public class CitySpinnerAdapter extends ArrayAdapter<City> {

private Context context;
private ArrayList<City> myObjs;

public CitySpinnerAdapter(Context context, int textViewResourceId,
                              ArrayList<City> myObjs) {
    super(context, textViewResourceId, myObjs);
    this.context = context;
    this.myObjs = myObjs;
}

public int getCount(){
    return myObjs.size();
}

public City getItem(int position){
    return myObjs.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    TextView label = new TextView(context);
    label.setText(myObjs.get(position).getName());
    return label;
}

@Override
public View getDropDownView(int position, View convertView,
                            ViewGroup parent) {
    TextView label = new TextView(context);
    label.setText(myObjs.get(position).getName());
    return label;
}}

这就是我创建旋转器的方式:

city2Spinner = (SearchableSpinner) findViewById(R.id.city2);

    CityDBHelper citydb = new CityDBHelper(getApplicationContext());

    ArrayList<HashMap<String, String>> cities2 = citydb.getCities();

    cities2Obj = new ArrayList<City>();
    for(HashMap<String, String> city2 : cities2){
        //for(String key : province.keySet()){
        //String name = province.get(key);
        cities2Obj.add(new City(Integer.valueOf(city2.get("id")), Integer.valueOf(city2.get("orig_id")), city2.get("name"), Integer.valueOf(city2.get("pid"))));
        //}
    }

    CitySpinnerAdapter city2Adapter =
            new CitySpinnerAdapter(AddProspectActivity.this,
                    android.R.layout.simple_spinner_item, cities2Obj);
    //adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    city2Spinner.setTitle("Select City");
    city2Spinner.setPositiveButton("OK");


    city2Spinner.setAdapter(city2Adapter);

我真的很困惑我应该在哪里更换物品。请帮忙。我希望我很清楚。 :((我正在使用com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1)

1 个答案:

答案 0 :(得分:1)

试一试。解决方案是让您的City类覆盖toString()方法。我刚刚添加了代码来创建适配器以便清晰。

public String toString(){
     return name;
}

适配器示例:

List<City> cities = ... ;
// Initializing an ArrayAdapter
citySpinnerArrayAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.spinner_item, cities);
    citySpinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
    citySpinner.setAdapter(citySpinnerArrayAdapter);
    // setTitle and setPositiveButton
    citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
         //...

    });