如何解决如何将值从适配器传递到活动在oncreate方法中我正在获取值bt我希望在create方法中声明该值
mainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
long ProductId = Long.parseLong(i.getStringExtra("product_id"));
long CustomerId = 1;
int sizeId = 1; // this is where i need int value to be passed
int quantity = 201;
}
//here i am getting this id value successfully bt i want that value to be assigned to sideId int in on create method
@Override
public void onClickCheckBox(Integer id) {
Log.d(TAG,String.valueOf(id));
}
界面
public interface OnSizeClickInterface {
void onClickCheckBox(Integer id);
}
适配器
@Override
public void onBindViewHolder(@NonNull ViewHolder holder,int position) {
holder.checkBox.setText(pList.get(position).getCode());
holder.checkBox.setonClickListener(view -> onSizeClickInterface.onClickCheckBox(pList.get(position).getId()));
}
这就是我传递价值的地方,一切正常!正如我提到的那样,我希望该id值可以在create方法中使用 我希望我能尽快得到答案! 谢谢
解决方法
接口可以通过两种方式实现,一种是已经实现的方式,另一种是要在特定方法内使用的方式。
您必须更改代码。
public int sizeId;// Either initialize sizeId=1
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
long ProductId = Long.parseLong(i.getStringExtra("product_id"));
long CustomerId = 1;
int quantity = 201;
productSizeAdapter = new ProductSizeAdapter(this,pList,new OnSizeClickInterface() {
@Override
public void onClickCheckbox(int id) {
sizeId = id;//this is where i am getting perfect value
//You should use sizeId here because it is click event.
SizeQuantity sizeQuantity = new SizeQuantity(sizeId,quantity);
}
});
//If you want to use here than you have to initialized sizeId=1. But I don't think you want to use here,because it will be called only once not every time when clicked
//SizeQuantity sizeQuantity = new SizeQuantity(sizeId,quantity);
}
,
将sizeId
设置为全局变量,并在MainActivity的onClickCheckbox ()
中分配新值,然后您就可以从那里继续执行任务,例如更新视图。
MainActivity
private int sizeId = 1;
@Override
public void onClickCheckbox(Integer id) {
Log.d(TAG,String.valueOf(id));
sizeId = id;
// update views if required
// Perform any other tasks if required
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。