2010-10-27 51 views

回答

439

我不知道這件事,但給它一個鏡頭。

在strings.xml定義:

<string-array name="array_name"> 
<item>Array Item One</item> 
<item>Array Item Two</item> 
<item>Array Item Three</item> 
</string-array> 

在您的佈局:

<Spinner 
     android:id="@+id/spinner" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:drawSelectorOnTop="true" 
     android:entries="@array/array_name" 
    /> 

我聽說這並不總是對設計師的工作,但它編譯罰款。

+0

非常好,非常感謝! – cambraca 2010-10-27 03:00:14

+33

只是想補充一點,如果你想爲每個選擇的項目分開值,你可以指定'android:entryValues =「@ array/array_name_values」'。 – 2013-06-04 16:50:40

+2

一個簡單的筆記......從我的理解中,Spinners不支持'drawSelectorOnTop',因爲除了Spinner本身沒有獨立的選擇器。解決方案絕對有效,謝謝! – Jabari 2013-06-11 22:25:22

8

定義這個在你String.xml文件 和數組的名字是你想要的,如重量

<string-array name="Weight"> 
<item>Kg</item> 
<item>Gram</item> 
<item>Tons</item> 
</string-array> 

,這代碼你layout.xml

<Spinner 
     android:id="@+id/fromspin" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:entries="@array/Weight" 
    /> 

在你的Java文件如果你在活動中寫入該代碼,然後刪除getactivity,則在片段中使用交疊性

a = (Spinner) findViewById(R.id.fromspin); 

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(), 
       R.array.weight, android.R.layout.simple_spinner_item); 
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 

     a.setAdapter(adapter); 
     a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
      public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { 
       if (a.getSelectedItem().toString().trim().equals("Kilogram")) { 
        if (!b.getText().toString().isEmpty()) { 
         float value1 = Float.parseFloat(b.getText().toString()); 
         float kg = value1; 
         c.setText(Float.toString(kg)); 
         float gram = value1 * 1000; 
         d.setText(Float.toString(gram)); 
         float carat = value1 * 5000; 
         e.setText(Float.toString(carat)); 
         float ton = value1/908; 
         f.setText(Float.toString(ton)); 
        } 

       } 



      public void onNothingSelected(AdapterView<?> parent) { 
       // Another interface callback 
      } 
     }); 
     // Inflate the layout for this fragment 
     return v; 
    } 
+0

這對我更好。謝謝! – 2016-09-21 20:40:42

0

關於第一條評論:如果你這樣做,你會得到一個錯誤(在Android Studio中)。這是關於它脫離Android命名空間。如果您不知道如何解決此錯誤,請查看下面的示例。希望這可以幫助!

例-Before:

<string-array name="roomSize"> 
    <item>Small(0-4)</item> 
    <item>Medium(4-8)</item> 
    <item>Large(9+)</item> 
</string-array> 

示例 - 後:

<string-array android:name="roomSize"> 
    <item>Small(0-4)</item> 
    <item>Medium(4-8)</item> 
    <item>Large(9+)</item> 
</string-array> 
+0

不起作用。 XML文件希望他的'string-array'具有'name'屬性,並且不能識別'android:name'。 – 2017-08-29 15:24:54