Android – saves the values entered into edittexts of recyclerview
I have a recyclerview with an EditText for each line, allowing the user to enter a value
However, when the user rotates the screen, these values are reset to their default blank values
Therefore, I want to save the values in the list or map so that I can repopulate the list when restoring
But I don't know how to "traverse the current list" and get edittexts and extract values
resolvent:
If you take the following recyclerview.adapter implementation as an example, you will notice some things. The list containing data is static, which means that it will not be reset when the direction changes. We added textwatcher in EditText to allow us to update the value when modifying the value and track the position by adding labels in the view. Please note that this is my special method, and there are many solutions
demonstration edition
Adapter
public class SampleAdapter extends RecyclerView.Adapter{
private static List<String> mEditTextValues = new ArrayList<>();
public SampleAdapter(){
//Mocking content for the editText
for(int i=1;i<=10;i++){
mEditTextValues.add("I'm editText number "+i);
}
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new CustomViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.edittext,parent,false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
CustomViewHolder viewHolder = ((CustomViewHolder)holder);
viewHolder.mEditText.setTag(position);
viewHolder.mEditText.setText(mEditTextValues.get(position));
}
@Override
public int getItemCount() {
return mEditTextValues.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder{
private EditText mEditText;
public CustomViewHolder(View itemView) {
super(itemView);
mEditText = (EditText)itemView.findViewById(R.id.editText);
mEditText.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void afterTextChanged(Editable editable) {}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(mEditText.getTag()!=null){
mEditTextValues.set((int)mEditText.getTag(),charSequence.toString());
}
}
});
}
}
}
(GIF looks as if it is being reset because it is in a loop, so it is not.)