Pergunta

I have weird problem with ListView on android 2.3. Application is simple todo list with EditText and ListView. Each time you write text and press ENTER text is added to ListView. Problem happend when I add 3rd element, order in ListView mess up (3rd element become 1st). I solve this problem so I rebind data every time in getView but on that way I lose ViewHolder pattern optimization. On 4.0 I don't have problem with same code :). Does anyone know what is reason for this behaviour?

This is my getView method.

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

    final ViewHolder view;
    if(convertView == null) {

        convertView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.todo_single_row, parent, false);

        view = new ViewHolder();
        view.text = (TextView)convertView.findViewById(R.id.tvToDoText);
        view.date = (TextView)convertView.findViewById(R.id.tvToDoDate);

        convertView.setTag(view);
    }
    else
    {
        view = (ViewHolder)convertView.getTag();
    }

    view.text.setText(ToDoList.getInstance().getToDoList().get(position).getText());
    view.date.setText(ToDoList.getInstance().getToDoList().get(position).getDate().toString());

    return convertView;
}

I try also to sort my adapter but did not help :(.

Comparator<Item> comparator = new Comparator<Item>() {
         public int compare(final Item item1, final Item item2) {
                return item1.getText().compareToIgnoreCase(item2.getText());
              };
    };

public class Item {
private String text;
private Date date;

public Item(String text) {

    this.text = text;
    this.date = new Date(java.lang.System.currentTimeMillis());
}

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

}

Foi útil?

Solução

This actually happens because usually getView() processes rows in an order that Android determines. Many people think this is called sequentially and it's not, it's called within an order that establishes the Adapter.

You can, however, override this behavior. In that case, you could simply declare a Comparator. For instance, if the content of your rows are strings, this would be one way:

Comparator alphabeticalOrder = new Comparator<String>() {
  public int compare(final String str1, final String str2) {
    return str1.compareToIgnoreCase(str2);
  };
};

Afterwards, you simply set it on your Adapter.

adapter.sort(alphabeticalOrder);

Outras dicas

On 2.3 and earlier versions of Android list view elements are indexed by what is visible. You need to use listView.getFirstVisible() to get a specific element.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top