2012-04-18 78 views
0

嘿傢伙我想設置列表視圖上的第一項檢查,但代碼無法正常工作。listview checked

import android.app.ListActivity; 
import android.os.Bundle; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 

public class ListView1 extends ListActivity { 
@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     String[] names = new String[] { "Android", "Windows7", "Symbian", "iPhone", 
       "Android", "Windows7", "Symbian", "iPhone", 
       "Android", "Windows7", "Symbian", "iPhone" }; 
     setListAdapter(new ArrayAdapter<String>(this, 
          android.R.layout.simple_list_item_single_choice, 
          android.R.id.text1, names)); 
     ListView listView = getListView(); 
     listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 
     listView.setSelection(0); 
     listView.setSelected(true); 

    }} 

picture of the activity 我想第一個單選按鈕被選中 任何幫助,將不勝感激爲 問候 HP

+0

你是什麼意思由chec k? – confucius 2012-04-18 16:17:39

回答

2
ListView listView = getListView(); 
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 
listView.setSelection(0); 
listView.setSelected(true); 

下面替換上面的行:::使用

ListView listView = getListView(); 
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 
listView.setItemChecked(0,true); 
+0

得到這個錯誤listview無法解析 – user749015 2012-04-18 16:54:19

+0

對不起在listView上打錯了伎倆 – user749015 2012-04-18 16:56:50

+0

在listview中我的東西「v」很小必須是帽子 – 2012-04-18 16:56:57

0

你需要做自己的適配器(延伸BaseAdapter的)。而在getView你能做到這一點很容易:

if(position == 0)layout.findViewById("mycheckbox").setchecked(true) 
0

在情況下,你會堅持setItemChecked(int, boolean)

通過參考源代碼,我發現以下幾點:

public void setItemChecked(int position, boolean value) { 
     if (mChoiceMode == CHOICE_MODE_NONE) { 
      return; 
     } 

     if (mChoiceMode == CHOICE_MODE_MULTIPLE) { 
      mCheckStates.put(position, value); 
     } else { 
      boolean oldValue = mCheckStates.get(position, false); 
      mCheckStates.clear(); 
      if (!oldValue) { 
       mCheckStates.put(position, true); 
      } 
     } 

     // Do not generate a data change while we are in the layout phase 
     if (!mInLayout && !mBlockLayoutRequests) { 
      mDataChanged = true; 
      rememberSyncState(); 
      requestLayout(); 
     } 
    } 

最重要的線在這裏是

// Do not generate a data change while we are in the layout phase 

這意味着,即使檢查項目背後的數據發生變化時,可繪製不會改變

心靈它

和平...