这有效,但是当活动开始时它会自动烘烤'One',因为它是默认选中的。如何制作它以使微调框包含一个默认值,在实际对话框中不是“请选择一个类别”,或者至少不会自动选择“一个”。感谢
final String[] items = new String[] {"One", "Two", "Three"};
final Spinner catagorySpinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Expense1.this,
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
catagorySpinner.setAdapter(adapter);
catagorySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), items[position], Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}});
答案 0 :(得分:2)
默认情况下,如果没有选择任何内容,Android中的微调器会显示适配器中的第一个值。不幸的是,没有办法改变它。
在您的情况下,您可以将Choose a Category
添加到您的数组中:
final String[] items = new String[] {"Choose a category", "One", "Two", "Three"};
但在onItemSelected
内你必须处理这个问题,即:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position != 0) {
Toast.makeText(getApplicationContext(), items[position], Toast.LENGTH_SHORT).show();
}
}
答案 1 :(得分:0)
您可以在微调器中手动设置默认选定项目。
catagorySpinner.setSelection(2);
答案 2 :(得分:0)
这样就可以在单击微调器时更改数组适配器,从而使原来的值不再存在;在这种情况下“选择一个类别”
//final String selected;
final int a;
final int x = 1;
final ArrayList<String> items = new ArrayList<String>();
items.add("Select A Category");
final Spinner catagorySpinner = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(Expense1.this,
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
catagorySpinner.setAdapter(adapter);
final ArrayList<String> itemsTwo = new ArrayList<String>();
itemsTwo.add("one"); itemsTwo.add("two"); itemsTwo.add("three");
final ArrayAdapter<String> adapterTwo = new ArrayAdapter<String>(Expense1.this,
android.R.layout.simple_spinner_item, itemsTwo);
adapterTwo.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
/* on spinner click listener (not items inside) */
catagorySpinner.setOnTouchListener(new OnTouchListener(){
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
catagorySpinner.setAdapter(adapterTwo);
catagorySpinner.setSelection(a);
x++;
}
return false;
}
});
catagorySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// if the spinner has been opened or not
if(x!=1){
a = position;
//code to execute if spinner has been clicked and arrayAdapter has been updated
//in my case selected = myArray.get(position);
} else {
//code to execute if "choose a catagory" is still there
//in my case selected = "novalue";
}
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});