how do I set the listView to the ArrayAdapter, Android

喜你入骨 提交于 2019-12-14 03:24:48

问题


how do I set this arrayAdapter to my listView so it populates the listView on my screen?

for example:

   listview.setAdapter(MyAdapter);

here is the code for my MainActivity and 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

}


回答1:


Do the following in the class file where you want to set the adapter for the ListView :

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

I would recommend that you use the View holder and convertview pattern to create the listView as it will be more efficient.Here is a good explanation of how it works. If you want to refer to a code sample I have it on Github .

Hope this helps.




回答2:


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



回答3:


Call constructor of your adapter class

MyAdapter mAdapter=new MyAdapter(listOfInfo,MainActivity.this);
listView.setAdapter(mAdapter);


来源:https://stackoverflow.com/questions/15874049/how-do-i-set-the-listview-to-the-arrayadapter-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!