2017-08-24 41 views
0

我正在使用Android Studio創建一個使用java的應用程序,但我對它相當陌生,我的大部分體驗都是在Visual Studio中使用C#和Winforms。如何在啓動時檢查特定的複選框?

目前我有一個ListView與CheckBoxes裏面,我使用ArrayAdapter同步列表。

ArrayList<String> items = new ArrayList<>(); 
    items.add("Alpha"); 
    items.add("Bravo"); 
    items.add("Charlie"); 
    items.add("Delta"); 

    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.row_layout, R.id.chkText, items); 
    lv.setAdapter(adapter); 

    // Test 
    Toast.makeText(getApplicationContext(), "Count " + lv.getAdapter().getCount(), Toast.LENGTH_LONG).show(); 
    for (int j = 1; j < lv.getAdapter().getCount(); j++) 
    { 
     CheckBox cb = (CheckBox) lv.getAdapter().getItem(j); 
     cb.setChecked(true); 
    } 

getCount()會返回正確的值,但應用程序在嘗試檢查框時會崩潰。我在網上找到的所有答案似乎都過於複雜,因爲這樣一個簡單的任務。有沒有很好又簡單的方法,例如,當應用程序加載時,我可以選中「Bravo」和「Delta」框?

+1

'lv.getAdapter()'返回一個適配器,而不是複選框。 –

+0

錯過了一個部分,我的錯,它現在讀取: lv.getAdapter()。getItem(j); –

回答

1

獲得該複選框的真正方法需要您深入ListView子級,而不是適配器本身。

android - listview get item view by position

基本上,僅適配器存儲數據和「結合」的數據到視圖。適配器實際上並不持有視圖信息本身。

  • lv.getAdapter()回報你一個通用的,無類型Adapter<?>

  • 當你這樣做lv.getAdapter().getItem(j),返回你的Object,這隻能投作爲一個String,因爲你已經使用了ArrayAdapter<String>


更好的方式來處理這個問題,如果你犯了一個自定義類extends ArrayAdapter<String>,然後你就可以編寫自己的字段來存儲名爲mChecked這裏一個布爾值列表,例如,以及更新該列表的方法。

詳細地說,這裏的想法

private List<Boolean> mChecked = new ArrayList<>(); 

public void setChecked(int position, boolean checked) { 
    mChecked.set(position, checked); // Might throw out of bounds exception! 
    notifyDataSetChanged(); // Need to refresh the adapter 
} 

public boolean isChecked(int position) { 
    return mChecked.get(position); 
} 

@Override 
public void getView(...) { 
    ... 

    View rowView = ... ; 

    TextView tv = (TextView) rowView.findViewById(R.id.chkText); 
    tv.setText(getItem(position)); 
    Checkbox cb = (Checkbox) rowView.findViewById(R.id.checkbox); 
    cb.setChecked(isChecked(position)); 
} 

當你通過checkBox.setChecked(isChecked(position));

檢查箱子或不到底該適配器類的getView()方法將控制,你將不會在應用程序加載時設置框,而是在您初始化適配器時。

+0

我想我對View的用途感到困惑。在你的第一種方法中,如果我能得到一個View,那真棒,但我該怎麼處理它?我似乎無法發現getChild()或getItem()方法。 第二種方法,比如說我創建了一個自定義類,如果我無法使用當前適配器執行此操作,那麼如何讓setChecked()工作? 對不起,我對這很多新東西。一切似乎都倒退了。 –

+1

'lv.getChild()'。你會得到一些'View'對象,然後你必須爲'row_layout.xml'中設置的任何複選框ID設置'findViewById'。對於第二個選項,請參閱https://guides.codepath.com/android/Using-an-ArrayAdapter-with-ListView –

相關問題