【发布时间】:2020-07-31 18:00:31
【问题描述】:
我想从 Recycler 视图的编辑文本列表中获取值。
这是我在 Activity 类中用于从回收器视图中获取值的代码。 代码由 cmets 中的错误消息组成
private void getPriceQuantity() {
List<PriceQuantity> priceQuantitiesToAdd = new ArrayList<PriceQuantity>();
for(int i=0;i<priceQuantities.size();i++)
{
View view=priceQuantityRecyclerView.getChildAt(i);
if(view!=null)
{
// this is the error i am receiving
// java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable
// android.widget.EditText.getText()' on a null object reference
EditText price = view.findViewById(R.id.product_price);
Log.d(TAG," price is "+price.getText().toString());
EditText quantity = view.findViewById(R.id.product_quantity);
}
}
}
这是我在适配器类中的视图持有者:
public ViewHolder(@NonNull View itemView) {
super(itemView);
productPrice = itemView.findViewById(R.id.product_price);
productQuantity = itemView.findViewById(R.id.product_quantity);
deletePriceQuantity = itemView.findViewById(R.id.deletePriceQuantityButton);
linearLayout = itemView.findViewById(R.id.priceQuantity);
deletePriceQuantity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(priceQuantities.size() >1){
priceQuantities.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
}
}
});
}
这是来自 Adapter 类的 onBindView Holder
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
addImageView.setOnClickListener(v -> {
if(priceQuantities.size() <=2 ){
Log.d("clicked","Add image is clicked");
priceQuantities.add(new PriceQuantity());
Log.d("clicked","size of array list "+priceQuantities.size());
notifyDataSetChanged();
}
});
【问题讨论】:
-
问题已解决。这个链接很有帮助。 creospiders.com/2016/04/how-to-access-each-view-of-item-by.html
标签: java android android-studio android-recyclerview