Spinner with on Click Listener
I am using spinner that shows error when i am trying to extract the item id of the selected spinner item. My Code goes here:
public void dispspi()
{
spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter <String> adap= new ArrayAdapter(this, android.R.layout.开发者_JAVA技巧simple_spinner_item, level);
spinner.setAdapter(adap);
spinner.setOnItemClickListener(new OnItemClickListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3)
{
int item = spinner.getSelectedItemPosition();
p=item;
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
}
How to get the item id of the spinner? Any help is appreciated..Thanks in advance
IIRC, you should be using a selected listener, not click:
spinner.setOnItemSelectedListener(new OnItemSelectedListener()
Then you can add the override tag to your selected method.
private String selecteditem;
spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
selecteditem = adapter.getItemAtPosition(i).toString();
//or this can be also right: selecteditem = level[i];
}
@Override
public void onNothingSelected(AdapterView<?> parentView)
{
}
});
spinner3.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View v,
int postion, long arg3) {
// TODO Auto-generated method stub
String SpinerValue3 = parent.getItemAtPosition(postion).toString();
Toast.makeText(getBaseContext(),
"You have selected 222 : " + SpinerValue3,
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Yes you can use some OnItemSelectedListener
for work with selected item. But sometimes we would like to handle exactly click for spinner. For example hide keyboard or send some analytics etc. In this case we should use TouchListener
because OnClickListener
doesn't work properly with Spinner and you can get error. So I suggest to use TouchListener
like:
someSpinner.setOnTouchListener { _, event -> onTouchSomeSpinner(event)}
fun onTouchSomeSpinner(event: MotionEvent): Boolean {
if(event.action == MotionEvent.ACTION_UP) {
view.hideKeyBoard()
...
}
return false
}
you should have this in the listener(OnItemSelectedListener)
public void onNothingSelected(AdapterView<?> arg0) {
}
It might works without it but put it to be consistent but there might be other errors also, can you provide the error log ?
精彩评论