Android:Spinner setSelection by Tag

时间:2017-04-03 03:07:31

标签: android android-sqlite android-spinner

我定义BaseAdapter以使用SQL中的记录填充Spinner 我将Spinner中的item设置为等于SQL数据库中的记录ID。

public static class Refueling_Adapter extends BaseAdapter {
    private Context vContext;
    private List<Banziny.Refuel> mRefuelingList;
    //private int mListing;

    public Base_Adapter(Context vContext, List<AppTest.basic> mBaseList) {
        this.vContext = vContext;
        this.mBaseList = mBaseList;
    }

    @Override
    public int getCount() {
        return mBaseList.size();
    }

    @Override
    public Object getItem(int position) {
        return mBaseList.get(position);
    }

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

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

            convertView = View.inflate(vContext, R.layout.item_base, null);
            convertView.setTag(mBaseList.get(position).getBase_id());

            TextView Basename = (TextView) convertView.findViewById(R.id.txt_Base_name);
            Basename.setText(mBaseList.get(position).getBase_name());


        return convertView;
    }
}

如您所见,我将spinner项的Tag设置为等于SQL记录ID。 现在我只需要知道如何使用Tag等于SQL记录ID来为Spinner设置SetSelected。

int baseidtoselect = mBaseList.get(0).getBase_ID();

从数据库中检索到此ID,我需要在微调器中找到标签。

1 个答案:

答案 0 :(得分:0)

您可以使用此功能

public static void selectItemByTag(Spinner spinner, int tag) {
    Refueling_Adapter adapter = (Refueling_Adapter) spinner.getAdapter(); // it is Refueling_Adapter because your Spinner use Refueling_Adapter
    for (int position = 0; position < adapter.getCount(); position++) {
        if(((YourObjectModel)adapter.getItem(position)).getBase_id() == tag) { // YourObjectModel here is AppTest.basic
            spinner.setSelection(position);
            return;
        }
    }
}