简体   繁体   中英

How to Implement a Custom Font in a Fragment in Android Studio

I cannot get a custom font to work in a Fragment in Android Studio version 1.5. Here is what I have so far in the java document.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
    View view = inflater.inflate(R.layout.fragment_sponsors, container, false);
    Typeface myTypeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/COOPPBL.TTF");
    TextView tv = (TextView) view.findViewById(R.id.textview1);
    tv.setTypeface(myTypeface);

    return inflater.inflate(R.layout.fragment_sponsors, container, false);
}

And this is what I have in the pertinent XML code:

<TextView
    android:id="@+id/textview1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/sponsors"
    android:textSize="35sp"
    />

The font does not change and the output remains the default type. I have already created an assets folder in the main project folder, with a "fonts" sub-folder which contains the file "COOPBL.TTF". What am I missing? I feel like it is just a silly error; I am very new to the platform.

try this,

return the view which you inflate and set the custom font to textview.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
    View view = inflater.inflate(R.layout.fragment_sponsors, container, false);
    Typeface myTypeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/COOPPBL.TTF");
    TextView tv = (TextView) view.findViewById(R.id.textview1);
    tv.setTypeface(myTypeface);

    return view;
}

You can try this

@Override
public View onCreateView(
    LayoutInflater inflater, 
    ViewGroup container,
    Bundle savedInstanceState) {
       View v = inflater.inflate(R.layout.fragment_sponsors, container, false);

       TextView tv = (TextView) v.findViewById(R.id.textview1);

       Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/COOPPBL.TTF"");

       tv .setTypeface(font); 
       return v;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM