2013-04-08 71 views
-1

如何将此ArrayAdapter设置为我的listView,以便在我的屏幕上填充listView?如何将listView设置为ArrayAdapter,Android

例如:

listview.setAdapter(MyAdapter); 

这里是我的MainActivity和ListAdapter代码:

public class MainActivity extends Activity { 

CheckBoxInfo cbr; 

@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 = (ListView) findViewById(R.id.listView); 

} 

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 

}您的适配器类的

回答

0

不要在类文件下面要设置为ListView适配器:

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

我会建议您使用视图架和convertview模式创建,因为它会更高效的ListView 。 Here是一个很好的解释它是如何工作的。如果你想参考一个代码示例,我可以在Github上找到它。

希望这会有所帮助。

0
ListView listview = (ListView) findViewById(R.id.listView); 
listview.setAdapter(MyAdapter); 
+0

在MyAdapter上出现编译错误,无论我放在哪里。 ListView listview =(ListView)findViewById(R.id.listView); \t \t \t listview.setAdapter(MyAdapter); – Kevik 2013-04-08 08:04:05

+0

把logcat !!!! – 2013-04-08 08:05:30

0

调用构造

MyAdapter mAdapter=new MyAdapter(listOfInfo,MainActivity.this); 
listView.setAdapter(mAdapter); 
相关问题