Reputation: 3455
I have a requirement to show an AlertDialog
when selecting the 2nd item in Spinner
. I know that using onItemSelected
we can listen to the spinner selection & show a popup. The issue is when I select the 2nd item, the dialog appears but after closing the dialog and then again we select the same item, it won't show the dialog as onItemSelected
will not be invoked. Is there any workaround for this? Without using a custom Spinner
implementation.
Upvotes: 3
Views: 3521
Reputation: 1
try the code below:
spinner.setOnItemSelectedListener(this);
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch(arg2)
{
case 0:
{
Dialog dialog = new Dialog(getApplicationContext());
.......
dialog.show();
spinner.setSelection(0);
}
break;
}
[...]
Upvotes: -3
Reputation: 10529
Create a custom spinner
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
public class CustomSpinner extends Spinner {
OnItemSelectedListener listener;
private AdapterView<?> lastParent;
private View lastView;
private long lastId;
public CustomSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
initlistner();
}
@Override
public void setSelection(int position) {
if (position == getSelectedItemPosition() && listener != null) {
listener.onItemSelected(lastParent, lastView, position, lastId);
} else {
super.setSelection(position);
}
}
private void initlistner() {
// TODO Auto-generated method stub
super.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
lastParent = parent;
lastView = view;
lastId = id;
if (listener != null) {
listener.onItemSelected(parent, view, position, id);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
if (listener != null) {
listener.onNothingSelected(parent);
}
}
});
}
public void setOnItemSelectedEvenIfUnchangedListener(
OnItemSelectedListener listener) {
this.listener = listener;
}
}
Set Listener
private OnItemSelectedListener listener;
listener = new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
Pass the listener object to custom listener
cusSpinner.setOnItemSelectedEvenIfUnchangedListener(listener);
Upvotes: 4