效果图:
图1:
图2:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Spinner
android:id="@+id/sp_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:spinnerMode="dropdown"
android:dropDownWidth="250dp"
android:entries="@array/menu_type">
</Spinner>
</RelativeLayout>
在 res / values 目录下新建 menu_type.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="menu_type">
<item>苹果</item>
<item>香蕉</item>
<item>柠檬</item>
<item>西瓜</item>
</string-array>
</resources>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Spinner spType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spType = findViewById(R.id.sp_type);
// Splinner的监听事件
spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String info = (String) spType.getSelectedItem();
Toast.makeText(MainActivity.this,info,Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
直接点击运行即可 !
属性介绍:
android:spinnerMode="dialog" //显示模式
// dropdown —— 直接下拉模式
// dialog —— 对话框效果模式
演示对话框模式,如下图:
属性介绍:
android:dropDownWidth="250dp" // 下拉框宽度
值越大,宽度越宽
如下图:
总结: 【 常 用 属 性 】
1. android:entries="@array/menu_type" // 绑定XML文件找那个的数据源
2. android:spinnerMode="dropdown" // 显示模式
"dropdown" 直接下拉模式
"dialog" 对话框效果模式
4. android:dropDownWidth="250dp" // 下拉框宽度