[英]How to set fontStyle for each item in recyclerview
我有一個 ArrayList 字體,每個項目都有一個寫在 textview 中的“文本”,所以我試圖為 Recyclerview 中的每個項目設置不同的字體樣式。 如何為每個項目設置字體樣式。
//It's My Adapter class
public class FontAdapter extends RecyclerView.Adapter<FontAdapter.FontViewHolder>
{
ArrayList<FontModel> fontModelArrayList;
Context context;
int row_index=-1;
public FontAdapter(ArrayList<FontModel> fontModelArrayList, Context context) {
this.fontModelArrayList = fontModelArrayList;
this.context = context;
}
@Override
@NonNull
public FontViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
context= parent.getContext();
LayoutInflater layoutInflater=LayoutInflater.from(context);
View fontView= layoutInflater.inflate(R.layout.font_list_item,parent,false);
return new FontViewHolder(fontView);
}
@Override
public void onBindViewHolder(@NonNull FontAdapter.FontViewHolder holder, int position)
{
FontModel fontModel=fontModelArrayList.get(position);
holder.itemView.setOnClickListener(v -> {
row_index=position;
notifyDataSetChanged();
});
// for setting the background
// when you selected
if(row_index==position){
holder.fontLayout.setBackgroundResource(R.drawable.font_background_item2);
holder.fontTextView.setTextColor(Color.parseColor("#0F393B"));
}
else
{
holder.fontLayout.setBackgroundResource(R.drawable.font_background_item);
holder.fontTextView.setTextColor(Color.parseColor("#FFFFFFFF"));
}
}
@Override
public int getItemCount() {
return fontModelArrayList.size();
}
public static class FontViewHolder extends RecyclerView.ViewHolder
{
TextView fontTextView;
LinearLayout fontLayout;
public FontViewHolder(@NonNull View itemView)
{
super(itemView);
fontTextView=itemView.findViewById(R.id.fontStyleTextView);
fontLayout= itemView.findViewById(R.id.fontItemLinearLayout);
}
}
}
我將所有字體樣式放在這樣的字體文件夾中。 font/arabic.ttf等。 如何為每個項目設置不同的字體樣式。
public static ArrayList<FontModel> getAllFonts(){
ArrayList<FontModel> listOfFonts =new ArrayList<>();
listOfFonts.add(new FontModel(R.font.arabic));
..
..
..
..
so on
return listOfFonts;
}
你必須在onBindViewHolder
的末尾添加一些字體設置代碼
@Override
public void onBindViewHolder(@NonNull FontAdapter.FontViewHolder holder, int position) {
FontModel fontModel = fontModelArrayList.get(position);
// current code
Context ctx = holder.itemView.getContext();
Typeface typeface = ctx.getResources().getFont(fontModel.getFontResourceId());
//or
Typeface typeface = ResourcesCompat.getFont(ctx, fontModel.getFontResourceId());
fontTextView.setTypeface(typeface);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.