1. 程式人生 > >Android基礎(一)佈局4.下拉框

Android基礎(一)佈局4.下拉框

xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Spinner"/>
    <Spinner
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinner1"
        android:drawSelectorOnTop="false"/>
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Spinner2"/>
    <Spinner
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinner2"
        android:drawSelectorOnTop="false"/>
</LinearLayout>

java中onCreate方法:

private ArrayList<String> allcountries;
    private ArrayAdapter<String> aspnCountries;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner);
        findview1();
        findview2();

為下拉框插入資料有兩種方式 方式一:

 private static final String[] mCountries={"China","Russia","USA"};
    private void findview1()
    {
        Spinner spinner_c=(Spinner)findViewById(R.id.spinner1);
        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);
    }

1.allcountries.add(mCountries[i]);先是將資料放在陣列allcountries中 2. ArrayAdapter 陣列介面卡,陣列和檢視之間的橋樑 3. ArrayAdapter arrayAdapter = new ArrayAdapter( ArrayListDemo.this, android.R.layout.simple_list_item_1, adapterData); 第一個引數是該活動,第二個引數是一個佈局,使得陣列中的資料按該佈局顯示,第三個引數是資料 4.setDropDownViewResource 介面卡的方法,用於設定設定下拉列表下拉時的選單樣式 5. spinner_c.setAdapter()將介面卡運用於元件Spinner中 方式二

private void findview2()
    {
        Spinner spinner_2=(Spinner)findViewById(R.id.spinner2);
        ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this,R.array.countries,android.R.layout.simple_spinner_item);
        spinner_2.setAdapter(adapter);
    }

1.R.array.countries必須在資原始檔夾中有資源 2.R.layout.simple_spinner_item是一個樣式

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="countries">
        <item>Japan</item>
        <item>England</item>
        <item>France</item>
        <item>Germany</item>
        <item>India</item>
    </string-array>
</resources>