Spinner is simple and practical
•
Android
public class Spinner
extends AbsSpinner
implements DialogInterface.OnClickListener
<!--code display01-->
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner_city1"
android:entries="@array/city"
android:dropDownWidth="50sp"
android:popupBackground="#0ff"
android:spinnerMode="dropdown"/>
<!--code display02-->
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner_city2"
android:entries="@array/city"
android:dropDownWidth="10sp"
android:popupBackground="#0ff"
android:prompt="@string/prompt_name"
style="@android:style/Widget.Spinner" />
<resources>
<string name="app_name">Spinner</string>
<!--数组资源代码-->
<array name="city">
<item >北京</item>
<item >杭州</item>
<item >西安</item>
<item >成都</item>
</array>
</resources>
<!--code display03-->
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner_color"
android:dropDownWidth="100sp"
android:popupBackground="#0ff"
android:spinnerMode="dialog"/>
/*
* main.java
*/
package com.manu.spinner;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity {
private Spinner spinner;
private String[] colors = {"red","green","blue","yellow","pink"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//根据id获得Spinner组件
spinner = (Spinner) findViewById(R.id.spinner_color);
//创建适配器
//public ArrayAdapter (Context context,int resource,int textViewResourceId,T[] objects)
//参数(上下文,系统自带的TextView或自定义的用于显示子项的TextView,要显示的数据)
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,colors);
spinner.setPrompt("请选择喜欢的颜色!");
spinner.setAdapter(adapter);
}
}
/*
* code display04
* 为spinner添加事件监听器
*/
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent,View view,int position,long id) {
Toast.makeText(MainActivity.this,spinner.getItemAtPosition(position).toString()+" is selected!",Toast.LENGTH_SHORT).show();
}
//Spinner默认显示第一项
@Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivity.this,"no selected!",Toast.LENGTH_SHORT).show();
}
});
@H_ 945_ 403@@H_ 841_ 404@@H_ 841_ 404@
Get to know spinner for the first time and continue to understand and learn in depth in the future~
@H_ 841_ 404@@H_ 841_ 404@
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码