//示例主要内容
public class MyActivity extends Activity {
private Spinner spinner;
private TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.spinner);
text = (TextView) findViewById(R.id.text);
List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.custom_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
}
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:gravity="right"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee" />
//example R.layout.main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!--stuff-->
<View
android:id="@+id/anotherField1"
android:layout_width="match_parent"
android:layout_height="40dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:spinnerStyle"
android:addStatesFromChildren="true"
>
<TextView
android:layout_alignParentLeft="true"
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text Left" />
<Spinner
android:id="@+id/spinner"
android:layout_alignParentRight="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@null"
/>
</RelativeLayout>
<!--stuff-->
<View
android:id="@+id/anotherField2"
android:layout_width="match_parent"
android:layout_height="40dp" />
</LinearLayout>
结果:
使用一个样式来定制旋转器,图片中使用的样式为:
style="@android:style/Widget.Holo.Light.Spinner"
以下链接对我有效。
https://android--code.blogspot.in/2015/08/android-spinner-border-between-items.html
res/drawable/spinner_item_border.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#ff2632"/>
</shape>
</item>
<item android:bottom="2dp">
<shape android:shape="rectangle">
<solid android:color="#d7ffa2"/>
</shape>
</item>
然后
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="@drawable/spinner_item_border"
/>
扩展BaseAdapter
)。实现getView()
来定义spinner在选择项目时显示的视图。实现getDropDownView()
来定义spinner下拉菜单显示的视图。你可以轻松地让getView()
返回类似于LinearLayout
的东西,以便在左右两侧显示文本。