I want to close an Android spinner once I click outside of the Spinner. Is that even possible?
Now that being said, calling spin. onDetachedFromWindow(); from anywhere in your Activity should help you to close the spinner programatically.
Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one.
Spinner is a widget similar to a drop-down list for selecting items. In this tutorial, we show you how to do the following tasks : Render a Spinner in XML, and load the selection items via XML file also. Render another Spinner in XML, and load the selection items via code dynamically.
I've had some luck with this, even if it doesn't completely work.
public View getView(int position, View v, ViewGroup parent) {
if (v == null) {
LayoutInflater mLayoutInflater = mActivity.getLayoutInflater();
v = mLayoutInflater.inflate(R.layout.user_row, null);
}
View tempParent = (View) parent.getParent().getParent().getParent();
tempParent.setOnTouchListener(new MyOnTouchListener(mActivity));
mActivity.setOpen(true);
User getUser = mUsers.get(position);
return v;
}
public class MyOnTouchListener implements OnTouchListener{
private MyActivity mOverall;
public MyTouchListener(MyActivity overall) {
mOverall = overall;
}
public boolean onTouch(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
}
return false;
}
}
public class MySelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
setUser(pos); //or whatever you want to do when the item is selected
setOpen(false);
}
public void onNothingSelected(AdapterView<?> parent) {}
}
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.
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.
Try
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) v.setVisibility(View.GONE);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With