Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set custom font in RecyclerView adapter

I have a fragment that loads a RecyclerView but I want to add a custom font to the TextView within one of the RecyclerView's items. Where in my adapter should I set the font? Also how exactly do I set the font?

I can't use this code,

Typeface font = Typeface.createFromAsset((getAssets(),
            "myfont.ttf");

because I am not in the Activity. So how should I get the font?

This is my adapter,

public class DiscoverRecyclerAdapter
        extends RecyclerView.Adapter<DiscoverRecyclerAdapter.ViewHolder> {

    private String[] mDataset;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView mText;
        public ViewHolder(android.support.v7.widget.CardView v) {
            super(v);
            mText = (TextView) v.findViewById(R.id.text);
        }
    }

    public DiscoverRecyclerAdapter(String[] myDataset) {
        mDataset = myDataset;
    }

    @Override
    public DiscoverRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_discover, parent, false);
        ViewHolder vh = new ViewHolder((android.support.v7.widget.CardView)v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.mText.setText(mDataset[position]);
    }

    @Override
    public int getItemCount() {
        return mDataset.length;
    }
}

Where within the adapter should I set the font and how would I set the font?

like image 603
Gary Holiday Avatar asked Dec 10 '22 23:12

Gary Holiday


1 Answers

Where in my adapter should I set the font?

Either in onCreateViewHolder() or in your ViewHolder constructor.

So how should I get the font?

With that code. Create the Typeface in the Activity (or fragment, if the RecyclerView is in a fragment). Pass the Typeface into the DiscoverRecyclerAdapter. Use the Typeface in onCreateViewHolder(), either directly or by passing it to the ViewHolder constructor. In particular, create precisely one instance of the Typeface, not one per row.

like image 159
CommonsWare Avatar answered Dec 28 '22 23:12

CommonsWare