在XML文件中编写arraylist

时间:2014-01-09 14:55:18

标签: android xml listview arraylist hashmap

我正在尝试自定义列表视图以添加图像图标和文本视图。我有一个存储的数组列表需要先将其转换为XML文件。请帮我把这个数组列表(包含存储在FTP服务器上的文件名)写入存储在内部存储器中的xml文件中。

1 个答案:

答案 0 :(得分:0)

无需在xml文件中编写arraylist。只需创建一个适配器类,并在其构造函数中保存带有arraylist的上下文。

然后在初始化适配器类时传递活动中的arraylist数据,并通过getView()在自定义xml视图中添加所有数据。

修改

您的适配器类应该类似(假设您的自定义布局有2个视图,即一个textview和一个复选框):

 public class YourAdapter extends BaseAdapter {
 private ArrayList<HashMap<String, String>> mArrayListData= null;
 private Context mContext;

 //Define your constructor in which you pass your arraylist data with usable activity context 
 public StatusAdapter(Context mContext, ArrayList<HashMap<String, String>> mArrayListData) {
 this.mContext = mContext;
 this.mArrayListData= mArrayListData;
 }

 @Override
 public int getCount() {
   return data.length;
 }

 @Override
 public Object getItem(int position) {
    return position;
 }

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

 private class MyViewHolder {
   TextView fillData;
   CheckBox statusCheck;

    MyViewHolder(View v) {
        statusCheck = (CheckBox) v.findViewById(R.id.checkit);
        fillData = (TextView) v.findViewById(R.id.textViewFillData);
      }
   }

  //Do whatever you want to do with your custom layout here
  @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    final MyViewHolder holder;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.yourcustomlayout, null);
        holder = new MyViewHolder(view);
        view.setTag(holder);
    } else {

        holder = (MyViewHolder) view.getTag();
    }

          HashMap<String, String> value = new HashMap<String, String>();
    value = data.get(position);
          holder.fillData.setText(value.get("Your_HashMap_Key");
          holder.statusCheck.setText(value.get("Your_HashMap_Key");
    holder.statusCheck.setTextColor(Color.CYAN);

            return view;
      }
  }

And Your Activity使用appropreate context和arraylist数据初始化youradapter类,然后将适配器对象用作listadapter.Somethink,如:

YourAdapter mAdapter = new YourAdapter(YourActivity.this, your_arraylist);
your_list.setAdapter(mAdapter);

注意:我粗略地编写了这段代码,所以如果有的话请避免驼峰错误。谢谢你