2011-05-27 79 views
0

在我的应用程序中,我有一个列表与行,每个包含图像,文本和复选框。我覆盖了我的simpleadapter的getView方法,根据它在行中的位置为每个复选框添加一个标记(代码是http://www.heypasteit.com/clip/YME ... bs和bs1是布尔值)。这样我就可以知道当onCheckedChanged被调用时哪个复选框被改变了。但是,我需要手动设置各个复选框的状态。例如,将标记为“3”(复选框第3行)的复选框的状态设置为“true”。针对特定的复选框与列表视图中的标记

任何帮助,将不胜感激!

回答

0

您可以用布尔值数组替换您的方法。例如,如果数组中有15个元素,则可以创建一个布尔值[15],并在用户单击复选框时更改不同位置的状态,并在开始时设置初始状态。

不是一个完美的例子,但我希望你明白我的意思:

public class YourActivity extends Activity { 

protected boolean[] checkStates; 

protected void onCreate(android.os.Bundle savedInstanceState) { 
    //... Some of your code where you get a list of you objects 
    checkStates = new boolean[list.size()]; 
    // As an example, let's check some of them: 
    checkStates[3] = true; 
    checkStates[7] = true; 
    //.. Something more 
}; 

SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.rowsecond, new String[] {"icon", "name"}, new int[] {R.id.image1, R.id.text1}) { 
    public View getView(int position, View convertView, ViewGroup parent) { 
     final View v = super.getView(position, convertView, parent); 
     boxer = (CheckBox)v.findViewById(R.id.checkbox); 
     boxer.setTag(position); 
     boxer.setOnCheckedChangeListener(checkedChangeListener); 
     boxer.setChecked(checkStates[position]); 
     return v; 
    } 

    private final OnCheckedChangeListener checkedChangeListener = new OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) { 
      final Integer position = (Integer) buttonView.getTag(); 
      checkStates[position] = isChecked; 
     } 
    }; 
}; 

}

不要忘记调用yourAdapterInstance.notifyDataSetChanged(),如果你想更新复选框状态从checkedChangeListener的外部和初始的onCreate()方法之后;