0

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!

cinemandre
  • 62
  • 8
  • SUGGESTION: Here are two approaches: https://stackoverflow.com/a/24317764/421195. or https://stackoverflow.com/a/33949979/421195. See also setPadding() in the spinner adapter: https://stackoverflow.com/a/33340530/421195. – paulsm4 Jun 21 '22 at 14:03

1 Answers1

0

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

android:gravity="center"
azaLiza
  • 37
  • 3