Close Spinner On Click Outside Of Spinner
Solution 1:
I've had some luck with this, even if it doesn't completely work.
The spinner adapter's get view :
public View getView(int position, View v, ViewGroup parent) {
if (v == null) {
LayoutInflatermLayoutInflater= mActivity.getLayoutInflater();
v = mLayoutInflater.inflate(R.layout.user_row, null);
}
ViewtempParent= (View) parent.getParent().getParent().getParent();
tempParent.setOnTouchListener(newMyOnTouchListener(mActivity));
mActivity.setOpen(true);
UsergetUser= mUsers.get(position);
return v;
}
The ontouch listener :
publicclassMyOnTouchListenerimplementsOnTouchListener{
private MyActivity mOverall;
publicMyTouchListener(MyActivity overall) {
mOverall = overall;
}
publicbooleanonTouch(View v, MotionEvent event) {
if (mOverall.getOpen()) {
mOverall.getWindow().setContentView(R.layout.main); //reset your activity screen
mOverall.initMainLayout(); //reset any code. most likely what's in your oncreate
}
returnfalse;
}
}
The on item selected listener :
publicclassMySelectedListenerimplementsOnItemSelectedListener {
publicvoidonItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
setUser(pos); //or whatever you want to do when the item is selected
setOpen(false);
}
publicvoidonNothingSelected(AdapterView<?> parent) {}
}
The activity
Your activity with the spinner should have a global variable mOpen with get and set methods. This is because the ontouch listener tends to stay on even after the list is closed.
The limitations of this method:
It closes if you touch between the spinner and the options or to the side of the options. Touching above the spinner and below the options still won't close it.
Solution 2:
Try
@OverridepublicvoidonFocusChange(View v, boolean hasFocus) {
if (!hasFocus) v.setVisibility(View.GONE);
}
Solution 3:
I wanted to be able to determine when the spinner menu was displayed, and dismissed as well. After a lot of searching, there wasn't a lot of good solutions. I was able to accomplish this by doing the following:
Created a custom spinner class, and override the following method:
@OverridepublicbooleanperformClick() { this.isDropDownMenuShown = true; //Flag to indicate the spinner menu is shownreturnsuper.performClick(); }
In my Activity, override the method onWindowFocusChanged(boolean hasFocus). If hasFocus == true && the flag in #1 is set to true, then the spinner has been dismissed (can be either by selection or tapping outside the spinner).
@OverridepublicvoidonWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (actionBarSpinner.isDropdownShown() && hasFocus) { actionBarSpinner.setDropdownShown(false); //Do you work here }
}
Good luck!
Post a Comment for "Close Spinner On Click Outside Of Spinner"