0

I'm working with a custom ListView with custom Adapter which only has EditText and TextView in each row, the problem is in scroll, when there is something in the first row, for example, it doesn't matter how long is the text in the field, if it goes out of the screen while scrolling, then if I get back to it, it looses the text it had

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = inflater.inflate(R.layout.campos, viewGroup, false);
    TextView tv= itemView.findViewById(R.id.lblNumeroCampo);
    EditText txtCampo = itemView.findViewById(R.id.txtCampo);
    txtCampo.setText(elementos.get(i));
    tvNumero.setText("" + (i +1));
    return itemView;
}

I just want not to lose text that is in any field of the list, thanks to those who want to help me.

MD Naseem Ashraf
  • 1,030
  • 2
  • 9
  • 22

2 Answers2

0

I think you don't need to call the findViewById every time the getview action fired.

You can also use a holder class.

Your UI classes should be called once when the view class is null. The view class can save the holder class with setTag method then reuse them by getTag.

Here is my suggestion.

class ViewHolder
{
    TextView tvNumero;
    EditText txtCampo;
}

public View getView(int position, View view, ViewGroup viewGroup) {

    ViewHolder holder;

    if(view == null)
    {
        view = inflater.inflate(resource, viewGroup, false);

        holder = new ViewHolder();
        holder.tvNumero= view.findViewById(R.id.lblNumeroCampo);
        holder.txtCampo = view.findViewById(R.id.txtCampo);

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

    holder.txtCampo.setText(elementos.get(i));
    holder.tvNumero.setText("" + (i +1));

    return view;
}

Have a good coding.

tommybee
  • 2,409
  • 1
  • 20
  • 23
0

This happens because android calls getView() everytime the view goes out of visible space and appears again. Since you are creating a new view in your getView() method, there is no recycling happening. Everytime the getView() method is called, a new view is returned with no text in it.

As mentioned by @tommybee, you can use a view holder class that checks to see if the view has already been initialized and return the initialized view if called.

Alternatively, I would suggest you to use RecyclerView instead of ListView, which makes using ViewHolder pattern mandatory. Reason is explained clearly here

Nirup Iyer
  • 1,215
  • 2
  • 14
  • 20