Spinner
下拉列表(Spinner)是一个每次只能选择所有项中一项的部件。它的项来自于与之相关联的适配器中。
看一个例子:
Strings.xml中文件内容:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, UITest3Activity!</string>
<string name="app_name">UITest3</string>
<string name="spinner_prompt"></string>
</resources>
下拉列表中的xml文件内容:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="sports">
<item >足球</item>
<item >网球</item>
<item >篮球</item>
<item >乒乓球</item>
</string-array>
</resources>
布局中的文件内容:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="运动项目"/>
<Spinner
android:id="@+id/sportsSp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/spinner_prompt"
android:entries="@array/sports"/>
</LinearLayout>
Activity中的内容:
package cn.calss3g.activity;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.TextView;
public class SpinnerDemo extends Activity implements OnItemSelectedListener{
Spinner sportSp = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_layout);
findViews();
}
private void findViews() {
sportSp = (Spinner)this.findViewById(R.id.sportsSp);
sportSp.setOnItemSelectedListener(this);
//sportSp.performClick(); 这句话默认下拉菜单为打开状态
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
TextView tv = (TextView) arg1;
Log.i("TAG", tv.getText().toString());
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
效果: