我有一個ReciclerView,它使用一個名爲「SimpleItemRecyclerViewAdapter」的適配器。 ReciclerView中的每個項目都位於項目的「drawable」文件夾中。我能夠在TextView上設置測試,但我不確定如何爲圖像執行此操作。這裏是我得到的輸出...圖像應該出現在黑色方塊上,並且是一個ImageView小部件。在ViewAdapter上加載圖像資源
這裏是我的適配器代碼:
package uk.co.example.calculator.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import uk.co.example.calculator.R;
import uk.co.example.calculator.ui.activities.Currency;
public class SimpleItemRecyclerViewAdapter extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.RecyclerViewSimpleTextViewHolder> {
// The items to display in your RecyclerView
private List<Currency> items;
// Provide a suitable constructor (depends on the kind of dataset)
public SimpleItemRecyclerViewAdapter(List<Currency> items) {
this.items = items;
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return this.items.size();
}
// Replace the contents of a view (invoked by the layout manager)
// Involves populating data into the item through holder
@Override
public void onBindViewHolder(RecyclerViewSimpleTextViewHolder holder, int position) {
Currency currency = items.get(position);
holder.getName().setText(currency.name);
holder.getSymbol().setText(currency.symbol);
holder.getAsset().?????????; // WHAT SHOULD I PUT HERE TO LOAD THE IMAGE FROM THE RAW FOLDER
}
// Create new items (invoked by the layout manager)
// Usually involves inflating a layout from XML and returning the holder
@Override
public RecyclerViewSimpleTextViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.from(viewGroup.getContext()).
inflate(R.layout.currency_list_card_layout, viewGroup, false);
return new RecyclerViewSimpleTextViewHolder(itemView);
}
public class RecyclerViewSimpleTextViewHolder extends RecyclerView.ViewHolder {
private TextView name;
private TextView symbol;
private ImageView asset;
public RecyclerViewSimpleTextViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.currency_name);
symbol = (TextView) v.findViewById(R.id.currency_symbol);
asset = (ImageView) v.findViewById(R.id.currency_asset);
}
public TextView getName() {
return name;
}
public TextView getSymbol() {
return symbol;
}
public ImageView getAsset() {
return asset;
}
}
}
如何顯示包含在文件夾中繪製圖像上的任何詳細的幫助將不勝感激。
Hi @ Jonty800。謝謝回覆。我認爲你的回答很好,但是在實施你的解決方案後,Android Studio會警告我「無法解析符號getResources」。任何想法如何我可以解決這個錯誤?提前致謝。 – CBA110
@ CBA110 getResources是Activity或Context類的一部分。在一個適配器中,你必須傳遞一個上下文。因此,將適配器的構造更改爲'public SimpleItemRecyclerViewAdapter(列表項目,Context上下文)',然後使用'this.context = context;'設置一個全局變量。然後你可以做'context.getResources('需要的時候 –
Jonty800