我无法通过Typeface放置自定义字体,因为在编写createFromAsset时未显示getAssets()。
我用过getContext(),getActivity(),将资产放在项目中而不是src中,但都找不到soln。
请告诉我错误。
package com.example.shubhojit.careersafter10th.ViewHolder;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.shubhojit.careersafter10th.Interface.ItemClickListener;
import com.example.shubhojit.careersafter10th.R;
public class Courses_After10thViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtCourseName;
public ImageView courseImage;
public TextView txtCourseDuration;
Typeface courseName;
Typeface courseDuration;
private ItemClickListener itemClickListener;
public Courses_After10thViewHolder(View itemView) {
super(itemView);
txtCourseName = (TextView)itemView.findViewById(R.id.courses_after10th_name);
courseImage = (ImageView)itemView.findViewById(R.id.courses_after10th_image);
txtCourseDuration = (TextView)itemView.findViewById(R.id.courses_after10th_duration);
courseName = Typeface.createFromAsset(context.getAssets(),"Fonts/Antipasto-RegularTrial.ttf");
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
@Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}
最佳答案
在RecyclerView.ViewHolder
的范围内,您可以像以下代码所示获得Context
的句柄(为了使XML预览正常工作,它还考虑了View.isInEditMode()
):
/* obtain a handle to the parent RecyclerView */
this.mRecyclerView = (SomeRecyclerView) viewHolder.getParent();
/* obtain a handle to the it's Context */
Context context;
if(viewHolder.isInEditMode()) {context = ((ContextThemeWrapper) this.mRecyclerView.getContext()).getBaseContext();}
else {context = this.mRecyclerView.getContext();}
Fonts/Antipasto-RegularTrial.ttf
最有可能应该重命名为fonts/antipasto_regulartrial.ttf
,以便成为有效的资源描述符。资产和资源之间可能有所不同;请参见Fonts in XML-这说明了如何同时进行。关于android - 除MainActivity.class以外的其他类中无法识别getAssets(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52693054/