在ArrayAdapter方法,Android上获取变量的编译错误

时间:2013-04-08 08:32:38

标签: android listview android-arrayadapter

在下面的代码中获取“CheckBoxInfo”变量的编译错误,它是正确的但我得到错误,

  listview = (ListView) findViewById(R.id.listView);
    myAdapter = new MyAdapter(this, R.layout.row_layout, CheckBoxInfo);
    listview.setAdapter(myAdapter);

从文档中说:“要在Listview中表示的对象”,但CheckBoxInfo是要在listview中表示的对象。这有什么不对?

其余代码:

公共类MainActivity扩展了Activity {

CheckBoxInfo cbr;
private ListAdapter MyAdapter;
ListView listview;
MyAdapter myAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    cbr = new CheckBoxInfo();
    cbr.checkBoxName = "dfdjklfjdkljf";
    cbr.checkBoxState = true;

    listview = (ListView) findViewById(R.id.listView);
    myAdapter = new MyAdapter(this, R.layout.row_layout, CheckBoxInfo);
    listview.setAdapter(myAdapter);

}

public class MyAdapter extends ArrayAdapter<CheckBoxInfo> {

     private List<CheckBoxInfo> checkBoxList;
    private Context context;

    public MyAdapter(List<CheckBoxInfo> infoList, Context context) {
        super(context, R.layout.row_layout, infoList);
        this.checkBoxList = infoList;
        this.context = context;

        for(int i = 0; i <=12; i++){
            checkBoxList.add(cbr);
        }

    }

    public View getView(int position, View convertView, ViewGroup parent) {

        // First let's verify the convertView is not null
        if (convertView == null) {
            // This a new view we inflate the new layout
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.row_layout, parent, false);
        }
            // Now we can fill the layout with the right values
            TextView tv = (TextView) convertView.findViewById(R.id.textView1);
            CheckBox cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
            CheckBoxInfo cbi = checkBoxList.get(position);

            tv.setText(cbi.checkBoxName);

        return convertView;
    }

}  // end MyAdapter

}

另一个类,表示填充listview的对象:

public class CheckBoxInfo {
 Boolean checkBoxState;
 String checkBoxName;

 public CheckBoxInfo(){
   checkBoxState = false;
   checkBoxName = "";
 }

}

3 个答案:

答案 0 :(得分:1)

您应该在ArrayAdapter构造函数中传递一个CheckBoxInfo元素列表。

ArrayList<CheckBoxInfo> items = new ArrayList<CheckBoxInfo>();
// add elements to the list
(...)
myAdapter = new MyAdapter(this, R.layout.row_layout, items);

答案 1 :(得分:1)

传递给构造函数的参数中的错误

      listview = (ListView) findViewById(R.id.listView);
      List<CheckBoxInfo> ls = new ArrayList<CheckBoxInfo>();
      ls.add(cbr);
      myAdapter = new MyAdapter(ls, this);
      listview.setAdapter(myAdapter);

在CheckBoxInfo类中重写toString函数

public String toString(){
    return "Name : " + checkBoxName + " , Checked : " + checkBoxState;
}

答案 2 :(得分:0)

请参阅myAdapter类的构造函数只有2个参数。在您的代码中,您使用3个参数调用构造函数。