2
我有一個列表視圖我正在修改list_item.xml
到。 list_item.xml
只是一個帶有CheckBox
如何在獨特的ListView位置訪問視圖?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
佈局當我點擊這些複選框之一,我想其他複選框取消選中。所以在我的適配器getView
方法中,我將CheckBox
添加到CheckboxManager
singelton類。
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View list_item = convertView;//View Recycling
if (list_item == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
list_item = vi.inflate(R.layout.database_item, null);
}
DatabaseItem databaseItem = getItem(position);
if (databaseItem != null) {
TextView textView = (TextView) list_item.findViewById(R.id.database_name);
CheckBox checkBox = (CheckBox) list_item.findViewById(R.id.checkBox);
if (textView != null) {
textView.setText(databaseItem.getTitle());
}
if (checkBox != null) {
CheckboxManager cbm = CheckboxManager.getInstanceOf(activity);
cbm.addCheckbox(checkBox, databaseItem.getQuery());
}
}
return list_item;
}
在我CheckboxManager
單例類我積累CheckBox
意見爲ArrayList
。我將一個點擊監聽器設置爲複選框,並通過遍歷數組列表來檢查其中一個檢查框時取消選中它們。
問題是我的數組列表大小始終是一個!由於我正在調整list_item.xml
的五個實例,我預計會有五個獨特的CheckBox
視圖,但顯然只有一個,因爲我的ArrayList
只有大小1(也許是因爲視圖回收?)。
如何訪問所有複選框並全部取消選中它們?
編輯
public class CheckboxManager {
private ArrayList<CheckBox> cbs = new ArrayList<>();
private static CheckboxManager singleton = null;
private static Activity activity = null;
private CheckboxManager(Activity activity){ this.activity = activity;}
// This is the only class method; the rest are instance methods.
public static CheckboxManager getInstanceOf(Activity activity){
if(null == singleton) return new CheckboxManager(activity);
return singleton;
}
public void addCheckbox(CheckBox cb, String query){
addClickListener(cb, query);
cbs.add(cb);
}
private void addClickListener(final CheckBox cb, final String query){
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// A box has been checked
if(true == isChecked) {
uncheckOtherBoxes(cb);
Movies.swapCursor(getCursor(query), activity);
}
}
}
);
}
private void uncheckOtherBoxes(CheckBox cb){
int idx = cbs.indexOf(cb);
Log.v("TAG","Size of list is "+cbs.size());
for(int i=0;i<cbs.size();i++){
if(idx != i){
cb.setChecked(false);
}
}
}
private Cursor getCursor(String query){
SQLiteDatabase db = DatabaseHelper.getInstanceOf(activity).getDatabase();
return db.rawQuery(query, null);
}
}
嗯,不知道爲什麼,我應該搬到這條線到我的'onCreate'方法。根據你的第二點,我簡單地假設一個新的CheckBox視圖實例被適配器實例化並通過管理器插入到我的ArrayList複選框中。 –
認爲它可能會更好地作爲一個領域,以防萬一它正在創建一個新的實例。 –
我明白你的意思了。管理器是一個單例類,因此只有它的每一個實例,並且其中的複選框的數組列表是靜態的。包括在編輯中的類。 –