Spinner在代码中设置文字居中

  • 如果ArrayAdapter使用了simple_spinner_item.xml布局
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data) {
            @NonNull
            @Override
            public View getView(int position, View convertView, @NonNull ViewGroup parent) {
                return setCentered(super.getView(position, convertView, parent));
            }

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

            private View setCentered(View view) {
                TextView textView = view.findViewById(android.R.id.text1);
                textView.setGravity(Gravity.CENTER);//这里不一样
                return view;
            }

        };
  • 如果ArrayAdapter使用了simple_spinner_dropdown_item.xml布局
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, data) {
            @NonNull
            @Override
            public View getView(int position, View convertView, @NonNull ViewGroup parent) {
                return setCentered(super.getView(position, convertView, parent));
            }

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

            private View setCentered(View view) {
                CheckedTextView textView = view.findViewById(android.R.id.text1);
                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);//这里不一样
                return view;
            }

        };

两种布局样式不一样,查看sdk\platforms\android-18\data\res\layout发现,simple_spinner_dropdown_item.xml使用了android:textAlignment="inherit"属性,导致设置textView.setGravity(Gravity.CENTER)没有作用,应该使用textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER)指定文字位置

你可能感兴趣的:(Android基础)