从Spinner选择中获取适配器或对象值

时间:2014-07-10 20:14:42

标签: java android spinner adapter

这是我的微调器设置:

 ArrayAdapter<SubCategory> dataAdapter = new ArrayAdapter<SubCategory>(AddLocationActivity.this,
                            android.R.layout.simple_spinner_item, scList);

    // populate spinner
    s = (Spinner) findViewById(R.id.subCatSpinner);
    s.setAdapter(dataAdapter);
    s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
             // WHAT DO I PUT HERE TO GET ID? 
            }


        });
    }

以下是适配器填充的对象:

public class SubCategory {
    public String subcategory;
    public long subcat_id;

    public SubCategory(String subcategory, long subcat_id) {
        this.subcategory = subcategory;
        this.subcat_id = subcat_id;
    }

    public String toString() {
        return subcategory;
    }
}

它有两个属性:子类别和它的ID。

子类别填充适配器就好了,但我想在spinne上的那个选项中获取它的ID

1 个答案:

答案 0 :(得分:1)

您可以在适配器中使用getItem(),如:

SubCategory sc = dataAdapter.getItem(position);

您还需要将dataAdapter声明标记为final才能生效。