用户点击微调器,我提供了一堆使用Unit.toString()
方法显示值的Unit实例。该方法提供了一个包含全名和缩写的字符串。在用户做出选择之后,我只想在微调器中显示缩写,因为toString
方法的输出很长。
我的onCreate
方法中的初始化:
this.spinner = (Spinner)this.findViewById(R.id.om_addIngredientDialog_unit);
ArrayAdapter<Unit> adapter = new ArrayAdapter<Unit>(context, R.layout.om_addingredientdialog_spinner, R.id.om_addIngredientDialog_spinner, DAOUnit.getAllArray(this.dbAdapter.getMDb()));
this.spinner.setAdapter(adapter);
这是我的Unit
课程:
public class Unit implements Serializable{
private long id;
private String name;
private String abbreviation;
public Unit(){}
public Unit(long id, String name, String abbreviation){
super();
this.id = id;
this.name = name;
this.abbreviation = abbreviation;
}
public void setId(long id){
this.id = id;
}
public long getId(){
return id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAbbreviation(String abbreviation){
this.abbreviation = abbreviation;
}
public String getAbbreviation(){
return abbreviation;
}
@Override
public String toString(){
if(this.abbreviation == null || this.abbreviation.length() == 0){
return this.name;
}
StringBuilder sb = new StringBuilder();
sb.append(this.name).append("(").append(this.abbreviation).append(")");
return sb.toString();
}
}
有什么方法可以实现上述输出吗?谢谢你的帮助!
谢谢,
昆
答案 0 :(得分:2)
创建自己的ArrayAdapter
子类并覆盖getView()
,就像使用ListView
一样,使用缩写而不是普通的toString()
值。
答案 1 :(得分:0)
谢谢!这样做了:)
以下是我的更改:
ArrayAdapter<Unit> adapter =new SpinnerArrayAdapter(context, R.layout.om_addingredientdialog_spinner, R.id.om_addIngredientDialog_spinner, DAOUnit.getAllArray(this.dbAdapter.getMDb()));
this.spinner.setAdapter(adapter);
和适配器:
public class SpinnerArrayAdapter extends ArrayAdapter<Unit>{
private LayoutInflater inflater = null;
private int resourceLayout = 0;
public SpinnerArrayAdapter(Context context, int resourceLayout, int textViewResourceId, Unit[] units){
super(context, resourceLayout, textViewResourceId, units);
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.resourceLayout = resourceLayout;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
View view;
if(convertView == null){
view = this.inflater.inflate(this.resourceLayout, parent, false);
}else{
view = convertView;
}
Unit unit = this.getItem(position);
TextView textView = (TextView)view;
textView.setText(unit.getAbbreviation());
return view;
}
}
再次感谢:)