Notes Spinner class (drop-down list box):

It is indirectly inherited from ViewGroup and belongs to the container class component. It is usually used to provide a series of selectable list items for users to choose, so as to facilitate the user
's XML attributes supported by the Spinner class:

android:entries specifies the list item
android:prompt is used to specify the title of the drop-down list

When Android5.0 applies the default theme Theme.Holo, setting the android:prompt attribute can not see the specific effect. If Theme.Black is used, the title can be displayed in the pop-up drop-down list box

If the list item to be displayed in the drop-down list is known, you can save it in the array resource file, save it in the array resource file, and then use the array resource to specify the list item for the drop-down list box, which can be implemented in Implement a drop-down list box while writing Java code

Add a string array to the XML file:

<?xml version = “1.0” encoding = “utf-8”?>
<resources>
<string-array name = “ctype”>
<item>内容</item>
<item>内容</item>
</string-array>
<resources>

After adding a list option box, if you need to perform response processing after the user selects a different list item, you can add an OnItemSelectedListener event listener to the drop-down list box, get the selected value through the getItemAtPosition() method, and then use Toast.makeText The () method displays the obtained value:

Spinner 对象名1 = (Spinner)findViewById(R.id.组件ID);
	对象名1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent,View view,int position,long id){
			//获取选择项的值
		String 对象名2 = parent.getItemAtPosition(position).toString();
		//代码
}
	@Override
	public void onNothingSelected(AdapterView<?> parent) {
}
});

Specify the adapter for the drop-down list box to add list items:
a) Create an adapter object, usually using the ArrayAdapter class. First, you need to create a one-dimensional string array to save the list items to be displayed, and then use

ArrayAdapter类的构造方法ArrayAdapter(Context context,int textViewResourceId,T[] objects)实例化一个ArrayAdapter类的实例 例:
String[] ctype = new String[]{“全部”,”电影”,”图书”,”唱片”,”小事”};
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ctype);

b) An example of the option style when setting the drop-down list box for the adapter:

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

c) Associate the adapter with the selection list:

spinner.setAdapter(adapter);

After adding a drop-down list box on the screen, you can use the getSelectedItem() method of the drop-down list box to get the selected value of the drop-down list box.Example:

Spinner spinner = (Spinner)findViewById(R.id.spinner1);
spinner.getSelectedItem();

Guess you like

Origin blog.csdn.net/qq_42823109/article/details/93451506