2

I have a Spinner loaded with data from a database.

Unfortunately, every time the android activity (inside which the spinner exists) begins, the first item of the spinner gets selected automatically by default.

Is there a way to prevent this i.e. I don't want the first item of the spinner to get selected automatically unless and until selected by the user. In fact, I don't want any of the item to get selected until one being selected by the user. How can this be done?

Update 1:

I noticed something peculiar. When beginning an activity containing a Spinner which is populated with the spinner items locally stored in java (inside array), the toast displays the first spinner item as getting selected by default.

However, the peculiar thing is

When beginning an activity containing a Spinner which is populated with spinner items stored in a database, the toast isn't displaying the first spinner item as getting selected. Now, this pretty much solves my problem. But, even if I want to choose the first spinner item, I had to select some other spinner item, getting the toast for the some other spinner item and then

selecting the first item displays a toast saying that the first item being selected

When do I notice such peculiar thing happening?

I was trying out all possible means (at least most of them suggested in StackOverFlow) to prevent the spinner from selecting the first spinner item by default. I was noticing the above peculiar behavior every time I tried getting rid of the problem (with suggestions as mentioned from StackOverFlow). What I further noticed is that, the peculiar thing was happening even for other spinners that are getting populated with items from database.

ok, that's too much of text. But, has anyone got an explanation?

user3314337
  • 341
  • 3
  • 13

1 Answers1

1

You can override the getdropdownview method of the arrayadapter as

ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,  android.R.layout.simple_spinner_item, state){
    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {             

        View v = null;

        if (position == 0) {
            TextView tv = new TextView(getContext());
            tv.setHeight(0);
            tv.setVisibility(View.GONE);
            v = tv;
        } 
        else { 

            v = super.getDropDownView(position, null, parent);
        } 

        parent.setVerticalScrollBarEnabled(false);
        return v;
    }
};

This will make sure that you only see your first value in the selection area not in the drop down list.Also, before populating your list from your database you can insert an empty string. Like "" as the first value by using yourlist.add(""). This will give you the desired result. The overridden method is present here: https://stackoverflow.com/a/25967740/4282901

Community
  • 1
  • 1
Syed Osama Maruf
  • 1,895
  • 2
  • 20
  • 37