从RecyclerView EditText获取值?

时间:2017-03-21 10:03:45

标签: android android-recyclerview

我对recyclerView感到震惊,

image

此处,名称和余额字段来自两个不同的数组。 我需要的是,这里每行都有一个EditText字段。我需要访问每一行上的每个EditText。并从中获取值..总计显示在Total textView上。可能吗?我尝试了很多。我没有得到它。

我在这里附上我的课程。

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

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;
}

}

适配器

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;
}

}

5 个答案:

答案 0 :(得分:4)

我认为您正在寻找一个回调,这意味着每当一个EditTexts上的数字发生变化时,您也希望总数发生变化。 首先,您需要添加一个接口,

OnEditTextChanged界面

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

然后你还需要在适配器的构造函数中包含它。

在Adapter.java中

private List<DataHolder> mDataSet;
private OnEditTextChanged onEditTextChanged;

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

在适配器的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) {}
    });
}

将此数组添加到GroupCollectionFragment中,这样您就可以将值保存在片段中,并在需要时随时使用它们。

Integer[] enteredNumber = new Integer[1000];

在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));
}

如果您想要整个文件,请告诉我。我写了它并构建了apk,它运行得很好。

答案 1 :(得分:3)

您可以在完成键盘操作时获得价值。你只需要设置

android:imeOptions="actionDone" 在编辑文本。然后只使用下面的代码

 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;

                });

答案 2 :(得分:2)

TextChangedListener上使用EditText,并使用密钥作为行的订单/唯一键的ID保存新HashMap中的输入。

   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
  }
});

最后从HashMap获取值。

答案 3 :(得分:0)

我修改了@MeHdi的答案。 @MeHdi的答案几乎没有什么错误,这将成为一个大问题,当recyclerview中向上/向下滚动时,项目位置将更改,其值将更改或为空。我在recyclerview的单行中也有许多editText。感谢@MeHdi的想法。屏幕看起来像下面的enter image description here

  

OnEditTextChanged

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

在适配器类中全局以下声明

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

适配器类

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());
        }
    }
}
}
  

您在其中具有recyclerview的Activity类

// 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("");
}

答案 4 :(得分:0)

更好的绩效方法

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;
}

感谢Goku's answers,请随时为您自己的应用调整方法。