3 回答
TA贡献1942条经验 获得超3个赞
最好的方法是使用自定义适配器,然后您可以将对象列表(在您的情况下是“销售ID和名称列表”)传递给适配器而不仅仅是字符串列表,然后在选择的项目上,您将获得所选对象,然后您可以获得所需的任何id或名称,您可以按照此链接使自定义适配器 https://abhiandroid.com/ui/custom-spinner-examples.html
TA贡献1828条经验 获得超4个赞
我通过编辑代码来解决这个问题
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(0)+cursor.getString(1));
} while (cursor.moveToNext());
}
并在项目上的微调器上选择使用子字符串进行操作
spsupir.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
String label = parent.getItemAtPosition(position).toString();
String ids = String.valueOf(label).substring(0,1);
Log.d("label:", ids);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
已编辑的代码
String label = parent.getItemAtPosition(position).toString();
String ids = String.valueOf(label).substring(0,1);
Log.d("label:", ids);
TA贡献1780条经验 获得超5个赞
另一个解决问题
步骤 1 创建模型类
public class Sales {
String id_sales,nama;
public Sales(String id_sales, String nama) {
this.id_sales = id_sales;
this.nama = nama;
}
public String getId_sales() {
return id_sales;
}
public void setId_sales(String id_sales) {
this.id_sales = id_sales;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
@Override
public String toString() {
return nama;
}
}
步骤 2 从 SQLite 表销售中放入所有数据
//Data spinner supir
public ArrayList<Sales> getSpinnerSales(){
ArrayList<Sales> salesList = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + "sales";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
salesList.add(new Sales(cursor.getString(0), cursor.getString(1)));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return salesList;
}
步骤 3 生成 void 以使用 sqlite aa 活动中的数据
private void loadSpinnerSales() {
// database handler
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
ArrayList<Sales> salesList = db.getSpinnerSales();
ArrayAdapter<Sales> adapter = new ArrayAdapter<Sales>(this, android.R.layout.simple_spinner_dropdown_item, salesList);
spsales.setAdapter(adapter);
}
步骤 4 在 OnCreate 上加载方法
spsales = (Spinner) findViewById(R.id.spSales);
loadSpinnerSales();
spsales.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Sales sales = (Sales) parent.getSelectedItem();
Toast.makeText(getApplicationContext(),sales.getId_sales(),Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
添加回答
举报