若是套用simple_spinner_item或是simple_spinner_dropdown_item,而後直接在Spinner中用android
android:gravity="center"
是沒法讓Spinner中的文字居中的。ide
這是由於Spinner中的文字實際上是套在TextView中的(參考:http://www.douban.com/note/483280526/?type=like#sep)。this
一開始我想到的一種辦法:spa
在spinner外面嵌套一個LinearLayout,設置android:gravity="center",這樣spinner天然就居中了。這樣的缺點是隻能設置Spinner爲Wrap_content了。code
其實能夠這樣:component
simple_spinner_item.xml和simple_spinner_dropdown_item.xml其實都是在sdk\platforms\android-18\data\res\layout中的,那麼咱們能夠覆寫他們。orm
好比這樣覆寫:xml
把TextView中的gravity改一下,這個問題就解決了。blog
另外,StackOverflow上還有人給出其餘的方法:pdo
The component that actually creates the items for the
Spinner
is the adapter. So you should customize it (by overriding thegetView()
method) to return centeredTextView
widgets.In your case, replace the
new ArrayAdapter<String> ...
initialization with this code:ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, NomProjets) { @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); return view; } };