Reputation: 2295
I have a spinner control with setOnItemSelectedListener in my app, when I select an item of the spinner, the event onItemSelected will be launched. Now I hope to click a button to launch the onItemSelected event, how can I do? Thanks!
spinnerFolder.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
//Do Business Logic
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Upvotes: 1
Views: 485
Reputation: 2783
Just call the following from your button listener:
spinnerFolder.getOnItemSelectedListener().onItemSelected(spinnerFolder, spinnerFolder.getSelectedView(), spinnerFolder.getSelectedItemPosition(), spinnderFolder.getSelectedItemId());
That's all :-)
Upvotes: 1
Reputation: 14710
When you populate the spinner with some data, you will have some sort of list objects (Strings, custom object, whatever) in the SpinnerAdapter
, you'll keep a reference to that list, let's call it: private List<Object> dataList = ...
First of all I would create a method that would handle the specific data object: protected void doBusinessLogic(Object myObj) { // do the things that make you happy }
Then call this from listener as:
spinnerFolder.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
// args2 is the position from backed data list
doBusinessLogic(dataList.get(args2));
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Then from button listener you would call above method again, but the object index you would get is from spinnerFolder.getSelectedItemPosition();
:
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int dataIndex = spinnerFolder.getSelectedItemPosition();
doBusinessLogic(dataList.get(index));
}
});
Upvotes: 0
Reputation: 949
The third parameter (int arg2) of onItemSelected for your spinner is the position, so you can get the current selection by
String selection = (String) mSpinnerAdapter.getItem(position);
or use mSpinner.getItemAtPosition(position)
if you don't have a custom adapter.
Store the current selection somewhere and pick it up in the onClickListener for your button.
Upvotes: 0