CustomAdapter setText值不正确

时间:2013-06-07 15:09:04

标签: android listview

textView.setText将列表中的所有项目设置为相同的内容。如何创建ArrayList中所有元素的列表?我需要以某种方式指定位置吗?

public class CustomAdapter extends BaseAdapter {

     private Context ctx;
     private ArrayList<String> children;

     CustomAdapter (ArrayList<String> data, Context context, String log) { 
         this.ctx = context;
         this.children = data;
     }

     @Override
     public View getView(int position, View convertView, ViewGroup parent){ 

          LayoutInflater inflator = (LayoutInflater)ctx.getSystemService(LAYOUT_INFLATER_SERVICE);
          View v = inflator.inflate(R.layout.text_list, null);

          TextView textView = (TextView) v.findViewById(R.id.logText);
          System.out.println("Cyan");
          textView.setTextColor(Color.CYAN);
          System.out.println("LOG SIZE: " + log.size());

          for(int i = 0; i < children.size(); i++){
              textView.setText(children.get(i));
          }
          return textView;
     }

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

    @Override
    public Object getItem(int position) {

        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    } 
 }

}

1 个答案:

答案 0 :(得分:3)

对于应该使用的项目位置的每一行调用

getView()。您正在遍历每一行的所有子项,这意味着它多次设置TextView文本并登陆最后一个孩子的文本。你的方法看起来应该更像这样:

@Override
public View getView(int position, View convertView, ViewGroup parent){ 

    if(convertView == null)
    {
        LayoutInflater inflator = (LayoutInflater)ctx.getSystemService(LAYOUT_INFLATER_SERVICE);
        convertView = inflator.inflate(R.layout.text_list, null);
    }

    TextView textView = (TextView)convertView.findViewById(R.id.logText);
    System.out.println("Cyan");
    textView.setTextColor(Color.CYAN);
    System.out.println("LOG SIZE: " + log.size());
    textView.setText(children.get(position));

    return convertView;
}