亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java:如何在 RecyclerView Adapter 中為 ContextCompat

Java:如何在 RecyclerView Adapter 中為 ContextCompat

largeQ 2023-04-26 10:50:51
我找到了解決方案,但我仍然把我的問題留在下面。我使用setBackgroundResource而不是ContextCompat,解決方案:holder.mTextPar.setBackgroundResource(R.drawable.border_box);原問題:我需要使用 ContextCompat 設置我的項目元素背景,但我不知道將什么放入上下文這是我試過的:public Context context;@Overridepublic void onBindViewHolder(@NonNull GameViewHolder holder, int position) {  holder.mTextPar.setBackground(ContextCompat.getDrawable(context, R.drawable.border_box));}當我打開這個 GameAdapter“工作”的 Activity 時,應用程序立即崩潰并且錯誤報告更喜歡我有這個的這一行holder.mTextPar.setBackground(ContextCompat.getDrawable(context, R.drawable.border_box));
查看完整描述

3 回答

?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

所有告訴您將上下文作為參數的答案都是錯誤的或多余的,您已經有一種從視圖中獲取上下文的方法:


@Override

public void onBindViewHolder(@NonNull GameViewHolder holder, int position) {

  Context context = holder.itemView.getContext(); 

}


查看完整回答
反對 回復 2023-04-26
?
Helenr

TA貢獻1780條經驗 獲得超4個贊

在您的適配器構造函數中,添加上下文作為參數。


public Context context;


public YourAdapterClass(Context context){

    this.context = context;

}


@Override

public void onBindViewHolder(@NonNull GameViewHolder holder, int position) {

    holder.mTextPar.setBackground(ContextCompat.getDrawable(context, R.drawable.border_box));

}


查看完整回答
反對 回復 2023-04-26
?
一只名叫tom的貓

TA貢獻1906條經驗 獲得超3個贊

不清楚你說的是什么適配器,ArrayAdapter適配器RecyclerView;請提及;還可以編寫更多代碼來幫助其他人了解需要上下文的內容/位置。通常,如果它是RecyclerViewAdapter,則視圖的上下文將會,例如itemView.getContext(),如果是ArrayAdapter,則有一個getContext()方法。



查看完整回答
反對 回復 2023-04-26
  • 3 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號