2010-12-14 107 views
2

您好,我有關於Android微調問題Android的微調

我有一個由array.The數組填充微調是國名和國家電話區號上的每一行的陣列的

部分

<item>355 Albania</item> 
<item>213 Algeria</item> 
<item>376 Andorra</item> 
<item>244 Angola</item> 
<item>1264 Anguilla</item> 
<item>1268 Antigua and Barbuda</item> 
<item>54 Argentina</item> 

這是用於填充微調

final Spinner spnCountry = (Spinner) findViewById(R.id.countries); 
ArrayAdapter<CharSequence> adpCountry = ArrayAdapter.createFromResource(
     this, R.array.countries, android.R.layout.simple_spinner_item); 
adpCountry 
    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
spnCountry.setAdapter(adpCountry); 

我想告訴O我的Java代碼只有國家代碼在框中,並且打開微調框以顯示每行的國家名稱和代碼。

有人可以幫助我如何做到這一點?

謝謝

回答

2

加載微調器;

String[] countries = getResources().getStringArray(R.array.countries); 

ArrayAdapter<String> adpCountry = new ArrayAdapter<String>(); 
for(String country : countries) 
{ 
    String parts = country.split(" "); 
    String code = parts[0]; 

    adpCountry.addItem(code); 
} 

adpCountry.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
spnCountry.setAdapter(adpCountry); 

選擇一個項目;

spnCountry.setOnItemSelectedListener(new OnItemSelectedListener() 
{ 
    @Override 
    public void onItemSelected(AdapterView<?> arg0, View arg1, int index, long arg3) 
    { 
     String country = ""; 
     String[] countries = getResources().getStringArray(R.array.countries); 

     String selected = countries[index]; 
     String[] parts = selected.split(" "); 
     for(String part : parts) 
     { 
      country += part; 
     } 

     TextView txtName = findViewById(R.id.country_name); 
     txtName.setText(country); 
    } 

    @Override 
    public void onNothingSelected(AdapterView<?> arg0){ /* Unused */ } 
}); 

(出心髒的)

+0

你好,我已經試過你的代碼,但有一個錯誤12-16 15:40:27.961:ERROR/AndroidRuntime(245):java.lang中:致.UnsupportedOperationException 12-16 15:40:27.961:ERROR/AndroidRuntime(245):at java.util.AbstractList.add(AbstractList.java:411) 12-16 15:40:27.961:ERROR/AndroidRuntime(245) :At java.util.AbstractList.add(AbstractList.java:432) 12-16 15:40:27.961:ERROR/AndroidRuntime(245):at android.widget.ArrayAdapter.add(ArrayAdapter.java:178) The方法addItem(String)i s未定義類型ArrayAdapter 嘗試addItem並添加 – 2010-12-16 13:42:24

+0

另外我想要做的是:當微調顯示我想只可見國家代碼,當我點擊微調和列表打開我想看到國家代碼和國家名稱 – 2010-12-16 13:58:49

+0

你可以嘗試插入(code,adpCountry.getCount())? – Thys 2010-12-16 20:28:14