2

I am trying to populate spinner from an array. All is working fine but when i click on the spinner the view takes me to the last items of the array. So i need to scroll up to see the first item.

I want to get view from the beginning not from the end. Please look into my code. I used android:spinnerMode = "dialog" in my XML.

My spinner1 is showing last items in the view but all items are coming in right order.

public class Pinbyplace extends AppCompatActivity {

Spinner spinner1, spinner2, spinner3;
ArrayAdapter<String> adapter1, adapter2, adapter3;

public String[] state = {"Andaman and Nicobar Islands", "Andhra Pradesh", "Arunachal Pradesh", "Assam",
        "Bihar", "Chandigarh", "Chhattisgarh", "Dadar and Nagar Haveli",
        "Daman and Diu", "Delhi", "Goa", "Gujarat", "Haryana", "Himachal Pradesh",
        "Jammu and Kashmir", "Jharkhand", "Karnataka", "Kerala", "Lakshadeep",
        "Madya Pradesh", "Maharashtra", "Manipur", "Meghalaya", "Mizoram", "Nagaland",
        "Odhisa", "Pondicherry","Punjab", "Rajasthan", "Sikkim", "Tamil Nadu",enter code here
        "Tripura", "Uttaranchal", "Uttar Pradesh", "West Bengal", "Select State"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pincode_place);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

    spinner1 = (Spinner) findViewById(R.id.spinner1);
    spinner2 = (Spinner) findViewById(R.id.spinner2);
    spinner3 = (Spinner) findViewById(R.id.spinner3);

    adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, state) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            if (position == getCount()) {
                ((TextView)v.findViewById(android.R.id.text1)).setText("");
                ((TextView)v.findViewById(android.R.id.text1)).setHint(getItem(getCount()));
            }
            return v;
        }

        @Override
        public int getCount() {
            return super.getCount()-1;
        }
    };

    //adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(adapter1);
    spinner1.setSelection(adapter1.getCount());

    adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            if (position == getCount()) {
                ((TextView)v.findViewById(android.R.id.text1)).setText("");
                ((TextView)v.findViewById(android.R.id.text1)).setHint(getItem(getCount()));
            }
            return v;
        }

        @Override
        public int getCount() {
            return super.getCount() - 1;
        }
    };

    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    adapter2.add("Item 1");
    adapter2.add("Item 2");
    adapter2.add("Select District");

    spinner2.setAdapter(adapter2);
    spinner2.setSelection(adapter2.getCount());

    adapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            if (position == getCount()) {
                ((TextView)v.findViewById(android.R.id.text1)).setText("");
                ((TextView)v.findViewById(android.R.id.text1)).setHint(getItem(getCount()));
            }
            return v;
        }

        @Override
        public int getCount() {
            return super.getCount()-1;
        }
    };

    adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    adapter3.add("Item 1");
    adapter3.add("Item 2");
    adapter3.add("Select Place");

    spinner3.setAdapter(adapter3);
    spinner3.setSelection(adapter3.getCount());

}
 }

See the picture below:

enter image description here

enter image description here

UPDATE: I found a better and simple solution for this..

public class Pinbyplace extends AppCompatActivity {

Spinner spinner_state, spinner_district, spinner_place;
HintArrayAdapter hintAdapter_state, hintAdapter_district, hintAdapter_place;

public String[] state = {"Select State", "Andaman and Nicobar Islands","Andhra Pradesh",
        "Arunachal Pradesh","Assam","Bihar", "Chandigarh","Chhattisgarh",
        "Dadra and Nagar Haveli","Daman and Diu","Delhi", "Goa","Gujarat","Haryana",
        "Himachal Pradesh","Jammu and Kashmir","Jharkhand", "Karnataka","Kerala",
        "Lakshadweep","Madhya Pradesh","Maharashtra","Manipur", "Meghalaya","Mizoram",
        "Nagaland","Odisha","Puducherry","Punjab","Rajasthan", "Sikkim","Tamil Nadu",
        "Telangana","Tripura","Uttar Pradesh","Uttarakhand","West Bengal"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pincode_place);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

    spinner_state = (Spinner) findViewById(R.id.spinner1);
    spinner_district = (Spinner) findViewById(R.id.spinner2);
    spinner_place = (Spinner) findViewById(R.id.spinner3);

    hintAdapter_state = new HintArrayAdapter<>(getApplicationContext(), 0);
    hintAdapter_state.addAll(state);
    spinner_state.setAdapter(hintAdapter_state);

    spinner_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if(position > 0) {
                spinner_state.setSelection(position);
                String state_name = (String) spinner_state.getSelectedItem();
                Toast.makeText(getApplication(), state_name, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    hintAdapter_district = new HintArrayAdapter<>(getApplicationContext(), 0);
    hintAdapter_district.add("Select Distrcit");
    spinner_district.setAdapter(hintAdapter_district);

    spinner_district.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if(position > 0) {
                spinner_district.setSelection(position);
                String district_name = (String) spinner_district.getSelectedItem();
                Toast.makeText(getApplication(), district_name, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    hintAdapter_place = new HintArrayAdapter<>(getApplicationContext(), 0);
    hintAdapter_place.add("Select Place");
    spinner_place.setAdapter(hintAdapter_place);

    spinner_place.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if(position > 0) {
                spinner_place.setSelection(position);
                String place_name = (String) spinner_place.getSelectedItem();
                Toast.makeText(getApplication(), place_name, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

private class HintArrayAdapter<T> extends ArrayAdapter<T> {

    Context mContext;

    public HintArrayAdapter(Context context, int resource) {
        super(context, resource);
        this.mContext = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
        TextView texview = (TextView) view.findViewById(android.R.id.text1);
        texview.setTextColor(Color.BLACK);
        texview.setHintTextColor(Color.GRAY);

        if(position == 0) {
            texview.setText("");
            texview.setHint(getItem(position).toString()); //"Hint to be displayed"
        } else {
            texview.setText(getItem(position).toString());
        }

        return view;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View view;

        if(position == 0){
            view = inflater.inflate(R.layout.spinner_hint_list_item_layout, parent, false); // Hide first row
        } else {
            view = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
            TextView texview = (TextView) view.findViewById(android.R.id.text1);
            texview.setTextColor(Color.BLACK);
            texview.setText(getItem(position).toString());
        }

        return view;
    }
}
}
Nikhil Jain
  • 198
  • 2
  • 10

3 Answers3

6
 adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    adapter3.add("Item 1");
    adapter3.add("Item 2");
    adapter3.add("Select Place");

    spinner3.setAdapter(adapter3);
    spinner3.setSelection(adapter3.getCount());

Change To

spinner3.setSelection(0);

Beacuse spinner3.setSelection(adapter3.getCount()); means Spinner Postion Is your Array Size. So Spinner Goto Last Index ......

Maulik Santoki
  • 532
  • 4
  • 14
  • I set the setSelection to 0 but by doing this, my first element of the array is coming on the spinner hint(Highlighted). I added hint to my spinner as the last element of the array. That's why I am using `spinner1.setSelection(adapter1.getcount())` at the last. – Nikhil Jain Sep 14 '15 at 04:12
1

Try commenting these lines

spinner.setSelection()

What this does it sets the selected item in your spinner.

Here you have written like

spinner.setSelection(adapter.getCount())

So it is selecting the last item.

Edit

go through this link, can post the whole code but that seems redundant,

https://stackoverflow.com/a/27692614/2641726

Here in CustomSpinner class , in 'performClick()' method, set selection to 0 like below

this.setSelection(0)

But you will have to manage the states and work accordingly, and yes in your xml layout file replace Spinner with CustomSpinner.

Community
  • 1
  • 1
Satyen Udeshi
  • 3,223
  • 1
  • 19
  • 26
  • 2
    By doing this, the first element of the array is coming as Hint in the Spinner. My hint is present at the last element of the array. So what i want is my spinner show hint before selection but when i touch it then the view should starts from the beginning not from the end and also that hint element should not be present in the spinner list. – Nikhil Jain Sep 14 '15 at 04:13
  • yes i got what problem you are facing , i am updating my answer as there is no direct solution to this , you have to write a custom spinner and manager that accordingly, this is one solution that you can use , hope that helps – Satyen Udeshi Sep 14 '15 at 04:40
  • Thanks for your help.. +1 – Nikhil Jain Sep 15 '15 at 02:35
  • If it did solved your problem then you can accept it as answer as it can help others too .. btw you are welcome – Satyen Udeshi Sep 15 '15 at 04:08
0

Sorry to say none of above work for me. But spinner.setSelection(adapter.getCount()-1) work for me as getCount() is size, we must minus 1 to convert it to index. Otherwise will just OutofBound exception.

Thanks.

Alfred Loh
  • 87
  • 6