保存输入到RecyclerView的EditTexts中的值 [英] Saving the values entered into EditTexts of a RecyclerView
问题描述
我有一个RecyclerView
,其中每行还具有一个EditText
,允许用户输入一个值.
I have a RecyclerView
where each row also has an EditText
that allows the user to enter a value.
但是,当用户旋转屏幕时,这些值会重置为其默认空白值.
However when the user rotates the screen the values reset to their default blank values.
所以我想将值保存在List
或Map
中,以便在还原时重新填充列表.
So I wanted to save the values in a List
or Map
so I can refill the list on restore.
但是我不知道如何迭代当前列表"并获取EditTexts
并提取值.
However I don't know how to "iterate over the current list" and grab the EditTexts
and extract the values.
推荐答案
例如,以下面的RecyclerView.Adapter
实现为例,您会注意到一些事情.包含数据的List
是static
,这意味着在方向更改时不会将其重置.我们在EditText
上添加TextWatcher
,以允许我们在修改值时更新值,并且通过在视图中添加 tag 来跟踪位置.请注意,这是我的特殊方法,有很多解决方法.
If you take for example the following RecyclerView.Adapter
implementation, you'll notice a few things. The List
containing the data is static
meaning it will not be reset on orientation changes. We are adding a TextWatcher
to the EditText
to allow us to update the values when they are modified, and also we are keeping track of the position by adding a tag to the view. Note that this is my particular approach, there are many ways of solving this.
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看起来像是被重置了,因为它处于循环状态,不是)
(gif may look like it's being reset, since it's in a loop, it's not)
这篇关于保存输入到RecyclerView的EditTexts中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!