我在spinner android中遇到了困难,更具体地说是在数据保存部分。
首先,我要告诉你下面代码的目的是什么。
我想创建一个微调器,用户可以选择要购买哪个星球,然后当他/她点击提交按钮时,会出现一个吐司说"你想购买:...."然后是一个购买摘要,如username&价。
然而,在这个过程的中间,我很难保存每个微调器元素的id。
每次我选择"地球" (id = 1)&点击提交,吐司将始终返回"火星"其中id = 0.所以似乎问题是我的提交按钮将始终重置所选的id。我故意将planetSpinner()方法设置为返回int,因此我总是可以追踪" id"被退回。但同样,提交按钮总是会显示为id = 0。
任何人都可以帮助我吗?我真的很感激。谢谢。
Spinner代码(MainActivity.java)
public int planetSpinner(){
context = this;
List<String> categories = new ArrayList<String>();
categories.add("Mars($12 billions)"); //0
categories.add("Earth ($99 billions)"); //1
categories.add("Jupiter ($13 billions)"); //2
cSpinner = (Spinner) findViewById(R.id.coffee_spinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cSpinner.setAdapter(dataAdapter);
cSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "You selected: " + cSpinner.getItemAtPosition(position), Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivity.this, "Nothing selected", Toast.LENGTH_LONG).show();
}
});
return cSpinner.getSelectedItemPosition();
}
提交购买代码(MainActivity.java)
public void submitOrder(View view){
Toast.makeText(MainActivity.this, "You wanted to buy: " + planetSpinner(), Toast.LENGTH_LONG).show();
displayMessage(confirmationOrder(userName, price));
}
答案 0 :(得分:1)
你试试这个:
<2 x float>
答案 1 :(得分:1)
这是因为每次调用函数时都会重新初始化微调器。因此,所选值是第一项,这就是为什么你的函数总是返回0.希望有帮助。
答案 2 :(得分:1)
public class MySpinner extends Activity implements OnItemSelectedListener{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.coffee_spinner);
spinner.setOnItemSelectedListener(this);
List<String> categories = new ArrayList<String>();
categories.add("Mars($12 billions)"); //0
categories.add("Earth ($99 billions)"); //1
categories.add("Jupiter ($13 billions)"); //2
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}