Java 如何在recycler适配器类中使用getcontext()?
我有一个扩展了recyclerview.adapter的适配器类,我需要在这个类中使用以下代码,但它在“this”上有错误Java 如何在recycler适配器类中使用getcontext()?,java,android,android-recyclerview,this,Java,Android,Android Recyclerview,This,我有一个扩展了recyclerview.adapter的适配器类,我需要在这个类中使用以下代码,但它在“this”上有错误 public void addItems(int有多少个){ 如果(有多少个>0){ int lastInsertedIndex=11; 对于(int i=lastInsertedIndex+1;i在适配器的构造函数中传递上下文,如下所示: Context context; public YourAdapter( Context c) { this.context
public void addItems(int有多少个){
如果(有多少个>0){
int lastInsertedIndex=11;
对于(int i=lastInsertedIndex+1;i在适配器的构造函数中传递上下文,如下所示:
Context context;
public YourAdapter( Context c) {
this.context = c;
}
现在用这个上下文代替这个
要传递上下文,请执行以下操作:
mAdapter = new YourAdapter(getContext());
recyclerview.setAdapter(mAdapter);
如果您是从活动中使用适配器,请使用ActivityName.this代替getContext()。在活动中,您必须执行以下操作:
活动
mAdapter = new CardViewDataAdapter(bank_list, context);
recyclerView.setAdapter(mAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
我想你可以得到这样的结果:
适配器
public CardViewDataAdapter(ArrayList<Bank> bank_list, Context context) {
dataSet = bank_list;
ctx = context;
}
public CardViewDataAdapter(ArrayList银行列表,上下文){
数据集=银行名单;
ctx=上下文;
}
在回收器适配器类中
private Context context;
//some code...//
@Override
public CartListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context=parent.getContext(); //here get the context
View cartItemRow= LayoutInflater.from(parent.getContext()).inflate(R.layout.cartitem_row_detail,parent,false);
return new CartListViewHolder(cartItemRow);
}
在整个适配器类中使用它…不需要传递上下文或任何东西。在recyclerview中设置之前调用适配器时,必须传递活动上下文。@KrishnaJ如何做到这一点?context=getApplicationContext();
private Context context;
//some code...//
@Override
public CartListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context=parent.getContext(); //here get the context
View cartItemRow= LayoutInflater.from(parent.getContext()).inflate(R.layout.cartitem_row_detail,parent,false);
return new CartListViewHolder(cartItemRow);
}