无法在 ViewHolder 中设置自定义字体

Can't set custom typeface inside ViewHolder

我已经尝试了所有我能在 Whosebug 上找到的方法,但似乎没有任何效果。

问题是我无法更改 CardViewLayout 中任何 TextView 的字体。

我试过 xml 中的字体系列和文本外观 我已经通过这样做改变了它,但我收到错误 无法解析符号 'itemView'

代码:

public class cardAdapter extends ArrayAdapter<cardModel> {

public cardAdapter(Context context) {
    super(context, 0);
}

@Override
public View getView(int position, View contentView, ViewGroup parent) {
    ViewHolder holder;

    if (contentView == null) {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        contentView = inflater.inflate(R.layout.card_layout, parent, false);
        holder = new ViewHolder(contentView);
        contentView.setTag(holder);
    } else {
        holder = (ViewHolder) contentView.getTag();
    }

    cardModel spot = getItem(position);

    holder.title.setText(spot.title);
    holder.description.setText(spot.description);
    Glide.with(getContext()).load(spot.url).into(holder.image);

    return contentView;
}

private static class ViewHolder {

    public TextView title;
    public TextView description;
    public ImageView image;

    Typeface customTypeOne = Typeface.createFromAsset(itemView.getContext().getAssets(), "fonts/typefaceone.ttf");

    public ViewHolder(View view) {
        this.title = (TextView) view.findViewById(R.id.title);
        title.setTypeface(customTypeOne);
        this.description = (TextView) view.findViewById(R.id.description);
        this.image = (ImageView) view.findViewById(R.id.image);
        }
    }
}

but I'm getting the error Cannot resolve symbol 'itemView'

那是因为您没有任何名为 itemView.

的东西

首先,替换:

Typeface customTypeOne = Typeface.createFromAsset(itemView.getContext().getAssets(), "fonts/typefaceone.ttf");

与:

Typeface customTypeOne;

然后,在您的 ViewHolder 构造函数中,在底部添加:

customTypeOne = Typeface.createFromAsset(this.title.getContext().getAssets(), "fonts/typefaceone.ttf");

现在你正在调用 getContext() 存在的东西。