2013-09-26 110 views
5

Tôi tạo thành phần Spinner bên trong số LinearLayout của mình. Tôi muốn làm cho các giá trị khác với hiển thị. Tôi không muốn làm điều đó theo chương trình. Tôi muốn sử dụng mảng dưới đây.Sử dụng entryValues ​​với phần tử Spinner

<?xml version="1.0" encoding="utf-8"?> 
<resources> 

    <string-array name="select"> 
     <item>a</item> 
     <item>b</item> 
     <item>c</item> 
    </string-array> 

    <integer-array name="selectValues"> 
     <item>1</item> 
     <item>2</item> 
     <item>3</item> 
    </integer-array> 

</resources> 

Đơn giản. Nếu a mục đã chọn, tôi muốn nhận được 1 làm số nguyên. Đường lối là gì?

<Spinner 
     android:id="@+id/sSelect" 
     android:layout_width="179dp" 
     android:layout_height="60dp" 
     android:layout_gravity="center" 
     android:entries="@array/select" 
     android:entryValues="@array/selectValues" /> 

Khi tôi sử dụng ở trên với bên dưới.

public void onItemSelected(AdapterView<?> item, View arg1, int sort, 
      long arg3) { 
     // TODO Auto-generated method stub 
     String selectedItem = item.getItemAtPosition(sort).toString(); 
} 

Tôi chỉ có thể nhận dữ liệu dưới dạng chuỗi chứ không phải giá trị. Tôi có thể nhận được các giá trị hiển thị.

+0

thể trùng lặp của [Android - cấu hình Spinner sử dụng mảng] (http://stackoverflow.com/questions/1587028/android-configure-spinner-to-use-array) – naXa

Trả lời

12

Giữ giá trị được chọn dưới dạng TypedArray và truy cập các giá trị đó theo phương thức onItemSelected().

// Keep the selected values as TypedArray 
Resources res = getResources(); 
final TypedArray selectedValues = res 
     .obtainTypedArray(R.array.selectValues); 

Spinner spinner = ((Spinner) findViewById(R.id.sSelect)); 
spinner.setOnItemSelectedListener(new OnItemSelectedListener() { 

    @Override 
    public void onItemSelected(AdapterView<?> parent, View view, 
      int position, long id) { 
     //Get the selected value 
     int selectedValue = selectedValues.getInt(position, -1); 
     Log.d("demo", "selectedValues = " + selectedValue); 
    } 

    @Override 
    public void onNothingSelected(AdapterView<?> arg0) { 
     // TODO Auto-generated method stub 

    } 
}); 
+0

Bạn có thể cho tôi biết về Tài nguyên và hàm getResources? –

+0

['getResources()'] (http://developer.android.com/reference/android/content/Context.html#getResources()) là phương thức bạn có thể truy cập từ bất kỳ lớp hoạt động nào. – imranhasanhira

+0

Tôi rất tiếc là đã dừng lỗi? –