2013-04-18 35 views
0

我從服務器檢索到的以下數據:稀疏數組作爲單一選擇的ListView

[ 
    {id: 8, name: "Item1"}, 
    {id: 14, name: "Item2"}, 
    {id: 30, name: "Item3", active: true}, 
    {id: 42, name: "Item4"} 
] 

我希望把這些數據轉化爲單一選擇的ListView(在對話框中,使用setSingleChoiceItems())和用戶做出選擇後,發送項目標識返回到服務器。

如何做到這一點?我唯一想到的解決方案是使用一些幫助程序數組,它可以在列表項(AFAIK必須順序執行)和項ID(非常隨機)之間進行映射。我也嘗試使用一些適配器,但沒有弄清楚如何。

回答

0

下面例子中使用單一選擇列表視圖給你:

的main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <ListView 
     android:id="@+id/listview1" 
     android:cacheColorHint="#00000000" 
     android:scrollbars="none" 
     android:fadingEdge="vertical" 
     android:soundEffectsEnabled="true" 
     android:dividerHeight="1px" 
     android:padding="5dip" 
     android:smoothScrollbar="true" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:drawSelectorOnTop="false" 
     android:layout_marginLeft="10dip" 
     android:layout_marginRight="10dip" 
     android:layout_marginBottom="10dip" 
     android:layout_weight="1"/> 

</LinearLayout> 

活動:

String[] items = new String[] { "Item1", "Item2", "Item3", "Item4" }; 
    int[] itemsIds = new int[] { 8, 14, 30, 42 }; 
    ListView listView = (ListView)findViewById(R.id.listview1); 
    listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, android.R.id.text1, items)); 
    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 
    listView.setOnItemClickListener(new OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, 
       long id) { 
      //here send your item id itemsIds[position] 
     } 
    }); 
+0

如果發送項目id事件onItemSelected()給你需要,然後使用onItemSelectedListener() – 2013-04-18 07:22:40