简体   繁体   English

从RecyclerView EditText获取值?

[英]Getting values from RecyclerView EditText?

I am struck in recyclerView, 我对recyclerView感到震惊,

图片

Here the name and balance fields are coming from two different arrays. 这里的名称和平衡字段来自两个不同的数组。 What I need is, here each row has an EditText field. 我需要的是,这里每行都有一个EditText字段。 I need to access each EditText on each row. 我需要访问每一行上的每个EditText。 And get values from it.. and a total is displayed on the Total textView. 并从中获取值..总计显示在Total textView上。 Is it possible? 可能吗? I tried a lot. 我尝试了很多。 I didn't get it. 我没理解。

i am attaching my classes here. 我在这附上我的课程。

MainActivity 主要活动

public class GroupCollectionFragment extends Fragment {
String[] nameArray = {"Akhil","Mohan","Anoop","Syam","Athul","Anish","Anand","Prasad","Mani","Oommen"
        ,"Akhil","Mohan","Anoop","Syam","Athul","Anish","Anand","Prasad","Mani","Oommen"
        ,"Akhil","Mohan","Anoop","Syam","Athul","Anish","Anand","Prasad","Mani","Oommen"};
String[] balanceArray={"2354","6578","2345","34654","2542","2354","6578","2345","34654","2542"
        ,"2354","6578","2345","34654","2542","2354","6578","2345","34654","2542"
        ,"2354","6578","2345","34654","2542","2354","6578","2345","34654","2542"};
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
LinearLayoutManager mLayoutManager;
List<DataHolder> holderList=new ArrayList<DataHolder>();

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootview=inflater.inflate(R.layout.group_collection_layout,container,false);
    mRecyclerView = (RecyclerView) rootview.findViewById(R.id.my_recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(getContext());
    mRecyclerView.setLayoutManager(mLayoutManager);
    setItems();
    mAdapter = new Adapter(holderList);
    mRecyclerView.setAdapter(mAdapter);
    return rootview;
}

private void setItems() {

    for(int i=0;i<nameArray.length;i++){
        DataHolder item=new DataHolder();
        item.setDname(nameArray[i]);
        item.setDbalance(balanceArray[i]);
        holderList.add(item);
    }
}

} }

DataHolder DataHolder

public class DataHolder {

String dname,dbalance;
public DataHolder(){
}
public String getDname(){
    return dname;
}
public void setDname(String name){
    this.dname=name;
}
public String getDbalance(){
    return dbalance;
}
public void setDbalance(String balance){
    this.dbalance=balance;
}

} }

Adapter 适配器

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<DataHolder> mDataSet;

public static class ViewHolder extends RecyclerView.ViewHolder{
    private TextView anameTxtView,abalanceTxtView;
    private EditText adepositEditText;
    public ViewHolder(View v){
        super(v);
        anameTxtView=(TextView)v.findViewById(R.id.nameTextView);
        abalanceTxtView=(TextView)v.findViewById(R.id.balanceTextView);
        adepositEditText=(EditText)v.findViewById(R.id.depositEditText);
    }
}

public Adapter(List<DataHolder> myData){
    mDataSet=myData;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.row_main,parent,false);
    ViewHolder vh=new ViewHolder(v);
    return vh;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.anameTxtView.setText(mDataSet.get(position).getDname());
    holder.abalanceTxtView.setText(mDataSet.get(position).getDbalance());


}

@Override
public int getItemCount() {
    return mDataSet.size();
}

@Override
public int getItemViewType(int position) {
    return position;
}

} }

I think you are looking for a callback, which means whenever a number on one of the EditTexts is changed you want the total number change too. 我认为你正在寻找一个回调,这意味着每当一个EditTexts上的数字发生变化时,你也希望总数发生变化。 So first of all you need to add an interface, 所以首先你需要添加一个界面,

OnEditTextChanged Interface OnEditTextChanged接口

public interface OnEditTextChanged {
    void onTextChanged(int position, String charSeq);
}

Then you need too include this in the constructor of the adapter. 然后你需要在适配器的构造函数中包含它。

In the Adapter.java 在Adapter.java中

private List<DataHolder> mDataSet;
private OnEditTextChanged onEditTextChanged;

public Adapter(List<DataHolder> myData, OnEditTextChanged onEditTextChanged) {
    mDataSet = myData;
    this.onEditTextChanged = onEditTextChanged;
}

In the onBindViewHolder of your Adapter you need to set a listener for text change and tell the fragment using onEditTextChanged object. 在适配器的onBindViewHolder中,您需要设置一个用于文本更改的侦听器,并使用onEditTextChanged对象告诉该片段。

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    holder.anameTxtView.setText(mDataSet.get(position).getDname());
    holder.abalanceTxtView.setText(mDataSet.get(position).getDbalance());

    holder.adepositEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            onEditTextChanged.onTextChanged(position, charSequence.toString());
        }

        @Override
        public void afterTextChanged(Editable editable) {}
    });
}

Add this array to your GroupCollectionFragment so you can save the values in your fragment and use them whenever you want them. 将此数组添加到GroupCollectionFragment中,以便可以将值保存在片段中,并在需要时使用它们。

Integer[] enteredNumber = new Integer[1000];

change your constructor call in GroupCollectionFragment 在GroupCollectionFragment中更改构造函数调用

mAdapter = new Adapter(holderList, new OnEditTextChanged() {
        @Override
        public void onTextChanged(int position, String charSeq) {
            enteredNumber[position] = Integer.valueOf(charSeq);
            updateTotalValue();
        }
    }); 

private void updateTotalValue() {
    int sum = 0;
    for (int i = 0; i < 1000; i++) {
        sum += enteredNumber[i];
    }

    totalValue.setText(String.valueOf(sum));
}

Let me know if you want the whole files. 如果你想要整个文件,请告诉我。 I wrote it and built the apk, it works just fine. 我写了它并构建了apk,它工作得很好。

You can get value at action done of keyboard. 您可以通过键盘操作获得价值。 all you need is to set 你只需要设置

android:imeOptions="actionDone" in edit text. 编辑文本中的android:imeOptions="actionDone" and then just use below code 然后只使用下面的代码

 adepositEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_DONE) {
                        // Do whatever you want here

                        return true;
                    }
                    return false;

                });

Use TextChangedListener on EditText and save input in new HashMap with key as a id of order/unique key for row. EditText上使用TextChangedListener并将输入保存在新的HashMap并使用key作为行的order / unique键的id。

   adeposit.addTextChangedListener(new TextWatcher() {

   public void afterTextChanged(Editable s) {}

  public void beforeTextChanged(CharSequence s, int start,
                                int count, int after) {
  }

 public void onTextChanged(CharSequence s, int start,
                           int before, int count) {
  // Save value her in HashMap
  }
});

At the end get Values from HashMap . 最后从HashMap获取值。

I have modified @MeHdi's answer. 我修改了@MeHdi的答案。 There is little fault in @MeHdi's answer which will turn into a big issue, When there is a scroll up/down in recyclerview, items position get changed and its values are getting changed or becoming empty. @MeHdi的答案几乎没有错,这将成为一个大问题。当在recyclerview中向上/向下滚动时,项目位置会发生变化,其值将变为空或变空。 Also I have number of editText in a single row of recyclerview. 另外,我在recyclelerview的一行中有一些editText。 Thanks to @MeHdi's idea. 感谢@ MeHdi的想法。 Screen looks like below 屏幕如下图所示 在此输入图像描述

OnEditTextChanged OnEditTextChanged

public interface OnEditTextChanged {
// here component_id is editTextId (findView by Id)
void onTextChanged(int component_id, int position, String charSeq);
}

Declare below in adapter class globally 在全局适配器类中声明如下

private Context context;
private List<DataModel> dailyLiqdateList;
private OnEditTextChanged onEditTextChanged;

Adapter class 适配器类

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder> {
private Context context;
private List<DataModel> dataList;

private OnEditTextChanged onEditTextChanged;

public MyAdapter(Context mContext, List<DataModel> dataList, OnEditTextChanged onEditTextChanged) {
    this.context = mContext;
    this.dataList = dataList;
    this.onEditTextChanged = onEditTextChanged;
}

@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View myHolder = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,parent,false);
    return new MyHolder(myHolder);
}
@Override
public int getItemCount() {
    return dataList.size();
}

 // This is important method due to which even if you scroll list, editText values will not get changed/empty. This method will maintain its position in recyclerview
@Override
public int getItemViewType(int position) {
    return position;
}

@Override
public void onBindViewHolder(MyHolder holder, int position) {

    holder.bind(dataList.get(position), position);

    holder.firstEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            onEditTextChanged.onTextChanged(R.id.item_firstEditText,position, holder.firstEditText.getText().toString());
        }
    });

    holder.secondEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            onEditTextChanged.onTextChanged(R.id.item_secondEditText, position, holder.secondEditText.getText().toString());
        }
    });


}

public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView headerName;
    EditText firstEditText, secondEditText;

    MyHolder(View itemView) {
        super(itemView);
        headerName = itemView.findViewById(R.id.headerNameTv);
        firstEditText = itemView.findViewById(R.id.item_firstEditText);
        secondEditText = itemView.findViewById(R.id.item_secondEditText);;

    }

    public void bind(final DataModel dto, int position) {
        if (dto != null) {
                headerName.setText(dto.getName());
        }
    }
}
}

Your Activity class in which you have recyclerview 您的Activity类,其中包含recyclerview

// declare these values globally
Integer[] firstValues, secondValues;
// Declare textviews for calculating and setting total values
private TextView firstTotalTv, secondTotalTv;

// Initialize editText values array list, same as dataList size.
firstValues= new Integer[dataList.size()];
secondValues= new Integer[dataList.size()];

// setting adapter on recyclerview, write this in onCreate()
myAdapter = new MyAdapter(thisActivity, dataList, new OnEditTextChanged() {
        @Override
        public void onTextChanged(int component_id, int position, String charSeq) {
            if (component_id == R.id.item_firstEditText) {
                if (Utils.isValidStr(charSeq)) {
                    firstValues[position] = Integer.valueOf(charSeq);

                } else {
                    firstValues[position] = null;
                }
                updateTotalValue1(firstValues, firstTotalTv);
            }

            if (component_id == R.id.item_secondEditText) {
                if (Utils.isValidStr(charSeq)) {
                    secondValues[position] = Integer.valueOf(charSeq);
                } else {
                    secondValues[position] = null;
                }
                updateTotalValue1(secondValues, secondTotalTv);
            }                
        }
    });
    recyclerView.setAdapter(myAdapter);


   // Update Method, write outside of onCreate()
   private void updateTotalValue1(Integer[] editTextList, TextView totalTextView) {
    int pSum = 0, c1Sum = 0;
    for (int i = 0; i < editTextList.length; i++) {
        if (editTextList[i] != null)
            pSum += editTextList[i];
        else if (i == 0 && editTextList[i] == null)
            pSum = 0;
    }
    if (pSum > 0)
        totalTextView.setText(String.valueOf(pSum));
    else
        totalTextView.setText("");
}

A better approach to performance 更好的性能方法

private List<Integer> getQuantityList() {
    List<Integer> quantities = new ArrayList<>();

    for (int i = 0; i < cartItems_rv.getChildCount(); i++) {
        quantities.add(Integer.valueOf(((EditText)Objects.requireNonNull(
                Objects.requireNonNull(cartItems_rv.getLayoutManager()).findViewByPosition(i))
                .findViewById(R.id.quantity_et)).getText().toString()));
    }

    return quantities;
}

thanks for Goku's answers , feel free to shape the method for your own app. 感谢Goku的回答 ,随意为您自己的应用程序塑造方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM