[英]Better way to get next higher or lower Integer from an Integer List
[英]Android: better way to get an integer from a spinner
我有一個填充整數值的微調器,我正在嘗試提取所選的值。 我設法使用以下代碼行:
Integer.decode(spinner.getSelectedItem().toString())
但這看起來像是一個簡單操作的很多要求。
我正在使用如下定義的字符串數組創建微調器:
在strings.xml中
<string-array name="settings_cells_array">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
</string-array>
在活動onCreate函數中:
Spinner spinner = (Spinner) findViewById(R.id.num_cells_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.settings_cells_array, R.layout.my_layout);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(R.layout.my_layout);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
在我看來,由於微調器是用字符串數組創建的,因此.toString()
調用似乎過多了,但我想這會為自定義對象構建的適配器和微調器帶來靈活性或類似的東西。
無論如何,我的問題是:
有沒有更好的方法從這種方式定義的微調器中提取整數,或者,有沒有更好的方法來設置我的微調器,以便它與int s更好地播放?
您可以做的是首先從資源獲取數組,然后創建一個Integer數組並將其提供給ArrayAdapter<Integer>
。 像這樣的東西:
Spinner spinner = (Spinner) findViewById(R.id.num_cells_spinner);
String[] array = getResources().getStringArray(R.array.settings_cells_array);
Integer[] intArray = new Integer[array.length];
for(int i = 0; i < array.length; i++) {
intArray[i] = Integer.parseInt(array[i]);
}
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,
android.R.layout.simple_spinner_dropdown_item, intArray);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
然后將getSelectedItem()
的結果轉換為Integer
:
Integer i = (Integer)spinner.getSelectedItem();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.