Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

view - how do I set the listView to the ArrayAdapter, Android

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

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...