2014-12-07 51 views
0

所以我查看了微調API,但它說我使用AdapterView事件處理,但我從來沒有創建一個適應。我在string.xml中創建了數組,然後使用 Android進行檢索:條目= @ array/arrayname檢索在微調器中挑選的對象

那麼,如何在沒有創建適配器的情況下檢索用戶在微調器中選擇的內容?或者我看着這個錯誤?

回答

0

谷歌是指通過實施適配器視圖什麼是你必須實現你的活動,例如其OnItemSelectedListener接口:

public class SpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener { 
    ... 

    public void onItemSelected(AdapterView<?> parent, View view, 
      int pos, long id) { 
     // An item was selected. You can retrieve the selected item using 
     // parent.getItemAtPosition(pos) 
    } 

    public void onNothingSelected(AdapterView<?> parent) { 
     // Another interface callback 
    } 
} 

,你必須設置的事件偵聽器是微調爲:

Spinner spinner = (Spinner) findViewById(R.id.spinner); 
spinner.setOnItemSelectedListener(this); 

這裏有一個完整的例子:

MainActivity

public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener { 

    //Spinner 
    private Spinner spinner; 
    //The array that will store the spinner items 
    private ArrayList<String> list; 

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

     //Create the spinner and add its listener 
     spinner = (Spinner)findViewById(R.id.spinner); 
     spinner.setOnItemSelectedListener(this); 

     //Spinner items, stored as a String array 
     list = new ArrayList<>(); 
     list.add("Item 1"); 
     list.add("Item 2"); 
     list.add("Item 3"); 
     list.add("Item 4"); 

     //To populate the spinner with a list of choices, you need to specify a SpinnerAdapter in your Activity or Fragment 
     ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list); 
     //Set the adapter to the spinner 
     spinner.setAdapter(adapter); 


    } 

    @Override 
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 

     //To Get the selected item: 
     //Since the spinner items are stored inside an array 
     //we can get the selected item text such as item.get(position) 
     Toast.makeText(this, list.get(position), Toast.LENGTH_LONG).show(); 
    } 

activity_main XML佈局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:orientation="horizontal"> 

    <Spinner 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/spinner" 
     android:background="#CCC" 
     /> 

</LinearLayout> 
+0

我怎麼有一個字符串包含什麼用戶精選微調串串= spinner.setOnItemSelectedListener(本); ? – Joe 2014-12-07 23:52:41

+0

試試這個String text = spinner.getSelectedItem()。toString(); – 2014-12-07 23:54:58

+0

微調控制器是字符串對象的數組我還需要轉換,因爲微調控制器是微調對象還是不是? – Joe 2014-12-07 23:56:55