Edittext values in listview changes to default on screen timeout

拜拜、爱过 提交于 2019-12-04 21:51:18

The views and the viewholders are only temporarily associated with a row. It means that any edited data needs to be stored elsewhere. Otherwise the information is lost every time the views are rebuild or reused for a different row, like when scrolling or rebuilding the view.

One possible solution is to add it to the model :

  • Add the data (quantity) to the ProductModel. (the_quantity)

  • Add a position attribute to the viewholder (the_position). This is needed because the listeners are anonymous classes. They see (a copy of) the value of the position parameter with the value it had when they were instanciated.
    This is why the compiler sometimes complains that the position parameter is not final, and it usually means that something is wrong : You should only reference it outside callbacks.

  • UI -> model : Store the edited value in model (in both listeners)

    public void onClick(View v) {
        //get the value of edittext
        //add one item
        int added_item = Integer.parseInt(viewHolder.quantity.getText().toString()) + 1;
    
        // Store the value in the model
        // We use the position from the viewholder,
        // **not** the method's parameter (which contain 
        // the value when the listener was created)
        modelItems.get(viewHolder.the_position).the_quantity = added_item;
    
        viewHolder.quantity.setText("" + added_item);
    }
    
  • Model -> UI : Update the UI each time, not only when the views a created

    // object item based on the position
    final ProductModel m = modelItems.get(position);
    viewHolder.tvTitle.setText(m.getname());      
    
    // update the viewholder's position 
    viewHolder.the_position = position;
    viewHolder.quantity.setText("" + m.the_quantity)
    
    return convertView;
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!