1 主类,主要包括用字符串方式和用从xml文件两种方式获取数组
package m.usewidget;
import java.util.ArrayList;
import java.util.List;
import m.usewidget.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class SpinnerActivity extends Activity {
Spinner spinner_c;
Spinner spinner_2;
private ArrayAdapter<String> aspnCountries;
private List<String> allcountries;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("SpinnerActivity");
setContentView(R.layout.spinner);
find_and_modify_view();
}
private static final String[] mCountries = { "AA" ,"BB", "CC",
"DD", "EE", "FF" };
private void find_and_modify_view() {
spinner_c = (Spinner) findViewById(R.id.spinner_1);
allcountries = new ArrayList<String>();
for (int i = 0; i < mCountries.length; i++) {
allcountries.add(mCountries[i]);
}
aspnCountries = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, allcountries);
aspnCountries
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_c.setAdapter(aspnCountries);
spinner_2 = (Spinner) findViewById(R.id.spinner_2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.countries, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_2.setAdapter(adapter);
}
}
2 文中用到的R.array.countries
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Used in Spinner/spinner_2.java -->
<string-array name="countries">
<item>AA</item>
<item>BB</item>
<item>CC</item>
<item>DD</item>
<item>EE</item>
<item>FF</item>
</string-array>
</resources>
<?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"
android:drawSelectorOnTop="false"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Spinner_2 From arrays xml file"
/>
<Spinner android:id="@+id/spinner_2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
/>
</LinearLayout>
3 效果图