Android Development 2020/4/10: Spinner drop-down box

  • Define components in layout

<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

</Spinner>

  • Use arrays to assign values ​​to spinner statically

Create arrays.xml under valid

Define array element assignment (only string array)

<string-array name = "spinner_string"> 
<item> Zhao Liying </ item>
<item> Dili Reba </ item>
<item> Yang Chaoyue </ item>
</ string-array>
use spinner ’s entries attribute
<Spinner
android:entries="@array/spinner_string"
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Spinner>
  • Use adapter

String [] strings = {"赵丽颖", "Dili 
Reba ", "杨 春雨"}; Spinner spinner = (Spinner) findViewById (R.id.spinner);
ArrayAdapter <String> adapter = new ArrayAdapter <String> ( this, R.layout.spinnerintem, strings);
spinner.setAdapter (adapter);
Note 1:
R.layout.spinnerintem is the layout of the item selected by sprinner. You can set the text information of the item (such as the center font size, etc.). Pay attention to the TextView layout
<?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="match_parent"
android:padding="10dp"
android:gravity="center"
android:textSize="12dp"
>

</TextView>

Note 2:
strings is the text information of itme
Note 3: Available
ArrayAdapter <String> and ArrayAdapter <Integer> etc. But the corresponding type belongs to the generic type
  • Set the listener for each item

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
TextView textView=(TextView)view;
Toast.makeText(MainActivity.this,textView.getText(),Toast.LENGTH_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}
});
说明:可以利用 TextView textView=(TextView)view;来设置每个itme的文本格式 字体大小 居中等


 

 

 







 

Guess you like

Origin www.cnblogs.com/miwujun/p/12670872.html