Table of contents
Example 1: (including adapter)
1. Introduction:
Android's Spinner is a drop-down menu control, usually used to select one of a set of options. It provides users with a simple way to interact with each other, allowing them to quickly and easily make selections about data within an application.
To use Spinner, you first need to create a Spinner element in your XML layout file. This element must contain an Adapter, which is responsible for binding data to the Spinner control. In the Java code, we need to set up a listener for the Spinner to respond when the user selects an option.
Spinner related properties:
- android:dropDownHorizontalOffset : Set the horizontal offset distance of the list box
- android:dropDownVerticalOffset : Set the horizontal and vertical distance of the list box
- android:dropDownSelector : The background when the list box is selected
- android:dropDownWidth : Set the width of the drop-down list box
- android:gravity : Set the alignment mode of the components inside
- android:popupBackground : Set the background of the list box
- android:prompt : Set the prompt information (title) of the list box in dialog mode. You can only reference the resource id in string.xml, but cannot write the string directly.
- android:spinnerMode : The mode of the list box, with two optional values: dialog : dialog-style window dropdown : drop-down menu style window (default)
- Optional attributes: android:entries : Use array resources to set the list items of the drop-down list box
2. Examples
Example 1: (including adapter)
The following is sample code for creating a Spinner control:
XML:
<Spinner android:id="@+id/my_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
In the above code, we create a Spinner control with id "my_spinner" and set its width and height. Next, we need to bind the adapter to this control. The following is sample code to bind an ArrayAdapter with a Spinner:
Bind data:
String[] items = {"Item 1", "Item 2", "Item 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<(this,android.R.layout.simple_spinner_item,items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = findViewById(R.id.my_spinner);
spinner.setAdapter(adapter);
In the above code, we first define an array containing string items. Next, we create an ArrayAdapter object and set its resource ID and data items. Finally, we bind the adapter to the Spinner control with the id "my_spinner".
Once the Spinner control is set up with the adapter, we need to set up a selection listener for it. The following is sample code for setting up Spinner's options listener in Java code:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// 记录当前选择的项
String selectedItem = (String) parent.getItemAtPosition(position);
Log.d("Spinner", "Selected item: " + selectedItem);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// 什么都不做
}
});
In the above code, we create an anonymous AdapterView.OnItemSelectedListener object and assign it to the Spinner control. When the user selects an item, the onItemSelected method will be called and we can read the selected option. If the user does not select any item, the onNothingSelected method will be called.
By using the Spinner control, we can easily let the user make selections in the application and perform the appropriate action upon selection. Whether selecting options in a form or selecting different views in an application, Spinner is a useful tool.
Complete code:
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context=".MainActivity">
<Spinner
android:id="@+id/my_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity:
package com.example.spinnerdemo02;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity {
private Spinner spinner;
// 下拉列表的数据
String[] items;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化界面
initView();
// 绑定数据
initData();
}
private void initData() {
items = new String[]{"Item 1", "Item 2", "Item 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
//
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// 记录当前选择的项
String selectedItem = (String) parent.getItemAtPosition(position);
Log.d("Spinner", "Selected item: " + selectedItem);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// 什么都不做
}
});
}
private void initView() {
spinner = findViewById(R.id.my_spinner);
}
}
Rendering:
Example 2 (without adapter):
Rendering:
Complete code:
MainActivity:
package com.example.spinnerdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener{
EditText name;
// 下拉列表
Spinner mSpinner;
// 复选框
CheckBox basketball,music,game;
// 单选框
RadioGroup mRadioGroup;
Button mButton;
// 性别
private String sex = "";
// 爱好
private String hobby = "";
// 班级
private String Class;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
name = findViewById(R.id.name);
mSpinner = findViewById(R.id.spinner);
mRadioGroup = findViewById(R.id.group);
mButton = findViewById(R.id.button);
basketball = findViewById(R.id.basketball);
music = findViewById(R.id.music);
game = findViewById(R.id.game);
// 使用RadioGroup监听Radio的变化
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId){
case R.id.man:
sex = "男";
break;
case R.id.woman:
sex = "女";
break;
default:
sex = "";
break;
}
}
});
// 注册复选框监听事件
basketball.setOnCheckedChangeListener(this);
game.setOnCheckedChangeListener(this);
music.setOnCheckedChangeListener(this);
// 下拉列表监听事件
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
// 当item被选中时调用该方法
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Class = MainActivity.this.getResources().getStringArray(R.array.position)[position];
}
// 当item没有被选中时调用
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// 按钮的监听事件
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "姓名:"+name.getText()+" 班级:"+Class+"性别:"+sex+" 爱好:"+hobby, Toast.LENGTH_SHORT).show();
}
});
}
// 复选框的监听事件
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// 获取按钮的文本
String msg = buttonView.getText().toString();
// 判断是否被选中
if(isChecked) {
if (!hobby.contains(msg)) {
hobby = hobby + msg;
}
}else{
if (hobby.contains(msg)){
hobby = hobby.replace(msg,"");
}
}
}
}
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名:"
android:textSize="20sp"
/>
<EditText
android:id="@+id/name"
android:layout_width="80dp"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="班级:"
android:textSize="20sp"
/>
<Spinner
android:id="@+id/spinner"
android:entries="@array/position"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="@+id/sex"
android:text="性别:"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioGroup
android:id="@+id/group"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/man"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男"
android:textSize="20sp"/>
<RadioButton
android:checked="true"
android:id="@+id/woman"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"
android:textSize="20sp"/>
</RadioGroup>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="爱好"
android:textSize="20sp"
/>
<CheckBox
android:id="@+id/basketball"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="篮球" />
<CheckBox
android:id="@+id/music"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="音乐"/>
<CheckBox
android:id="@+id/game"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="音乐"/>
</LinearLayout>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="提交"/>
</LinearLayout>
Create array.xml in res/value
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="position">
<item>计算机21-2</item>
<item>新能源20-1</item>
<item>电子19-1</item>
</string-array>
</resources>