Skip to content
Advertisement

How to center simple_spinner_dropdown_item in Android Studio?

I want to center the text of my simple_spinner_dropdown_item element, so I got this solution:

private void addCountriesToSpinner(){
    DatabaseHelper dhHelp = new DatabaseHelper(this);
    _countryNames = dhHelp.getAllCountryNames();

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, _countryNames){
        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            return setCentered(super.getView(position, convertView, parent));
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent){
            return setCentered(super.getDropDownView(position, convertView, parent));
        }

        private View setCentered(View view){
            TextView textView = (TextView)view.findViewById(android.R.id.text1);
            textView.setGravity(Gravity.CENTER);
            textView.setTextSize(18);
            return view;
        }
    };

However, this is just working for the simple_spinner_item where all the dropdown items are way to tight. But when ever I replace it by simple_spinner_dropdown_item the centering is no longer working.

I guess the answer lies in this line, but I dont know how to adapt:

TextView textView = (TextView)view.findViewById(android.R.id.text1);

Thanks!

Advertisement

Answer

In your XML file where you have declared the <Spinner>...</Spinner> element try to add this attribute (to the spinner) :

android:gravity="center"
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement