Spinner下拉列表装填数据的两种方法
Android中,给Spinner组件装填数据比较常见的有以下两种方法:
一、编程载入列表数据
效果图:
首先,在布局文件main.xml中添加spinner组件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Spinner_1"
/>
<Spinner
android:id="@+id/spinner_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
然后,在MainActivity.java中,自定义方法add_list()进行Spinner的数据装载,代码如下:
public class MainActivity extends Activity {
private static final String[] mCountries = { "中国", "美国", "日本",
"俄罗斯", "加拿大" };
Spinner sp = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
add_list();
}
private void add_list() {
sp = (Spinner) findViewById(R.id.spinner_1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.易做图_spinner_item, mCountries);
adapter.setDropDownViewResource(android.R.layout.易做图_spinner_dropdown_item);
sp.setAdapter(adapter);
}
}
二、在XML中预定义列表数据
首先,在strings.xml中定义列表数据,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, MainActivity!</string>
<string name="app_name">SpinnerTest</string>
<string-array name="countries">
<item>中国</item>
<item>美国</item>
<item>日本</item>
<item>俄罗斯</item>
<item>加拿大</item>
</string-array>
</resources>
其次,在布局文件main.xml中添加spinner组件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Spinner_1"
/>
<Spinner
android:id="@+id/spinner_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
最后,在MainActivity.java中,进行Spinner的数据装载,代码如下:
public class MainActivity extends Activity {
Spinner sp = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sp = (Spinner) findViewById(R.id.spinner_1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.countries,
android.R.layout.易做图_spinner_dropdown_item);
sp.setAdapter(adapter);
}
}
本文出自 “Android学习心得” 博客
补充:移动开发 , Android ,