Android:如何设置列表视图的子项?

时间:2014-03-31 12:45:25

标签: android listview

我正在使用两个String数组:

String[] crs //Contains an array of Student name's

 String[] crsn  // Contains their roll no's

我打算做的是将列表项值设置为学生姓名和子项目作为roll no

我使用以下方法显示列表视图项,但它只显示学生名而不是子项。

我如何编写用于显示子项的代码,即Roll no's数组。

    try {

            setListAdapter(new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_checked, new ArrayList()));
            ListView listView = getListView();
            listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

            new AddStringTask().execute();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Null", Toast.LENGTH_LONG)
                    .show();
        }
class AddStringTask extends AsyncTask<Void, String, Void> {
        @Override
        protected Void doInBackground(Void... unused) {
            for (int i = 0; i < crs.length; i++) {
                publishProgress(crs[i]);
            }
            return (null);
        }

        @Override
        protected void onProgressUpdate(String... item) {
            ((ArrayAdapter) getListAdapter()).add(item[0]);
        }

        @Override
        protected void onPostExecute(Void unused) {
            setSelection(3);

        }
    }

我是android的初学者,所以PLZ任何建议都热烈欢迎....谢谢

1 个答案:

答案 0 :(得分:0)

您只需在Listview创建中使用此自定义适配器,然后您将在此块中编写代码...

use this code in your activity...

CustomAdapter mAdapter = new CustomAdapter(this, R.layout.listitem, mListItems);
  mPullRefreshListView.setAdapter(mAdapter);

然后在这里替换你的布局......

public class CustomAdapter extends ArrayAdapter<Sample> {

public ArrayList<Sample> mlist;
public Context context;
public LayoutInflater inflater;

public CustomAdapter(Context context, int resource, ArrayList<Sample> mlist) {
    super(context, resource);
    this.mlist = mlist;
    this.context = context;
    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getPosition(Sample item) {
    return super.getPosition(item);
}

@Override
public Sample getItem(int position) {
    return mlist.get(position);
}

@Override
public int getCount() {
    return mlist.size();
}

@Override
public long getItemId(int position) {
    return super.getItemId(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    convertView = inflater.inflate(R.layout.listitem, null);// Replace your
                                                            // layout....
    TextView text1 = (TextView) convertView.findViewById(R.id.item1);
    TextView text2 = (TextView) convertView.findViewById(R.id.item2);
    text1.setText(mlist.get(position).getListitem1());
    text2.setText(mlist.get(position).getListitem2());       
    return convertView;
}

}