简体   繁体   中英

How to set a font for specific textview in Android?

I followed the steps from this and it crashes my app when running. Below is my entire code.

public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        TextView tx = (TextView)findViewById(R.id.textView5);
        Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/myriad_pro_regular.ttf");
        tx.setTypeface(tf);
        setContentView(R.layout.activity_main);
    }
}

When I add the below codes

TextView tx = (TextView)findViewById(R.id.textView5);
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/myriad_pro_regular.ttf");
tx.setTypeface(tf);

The app crashes and I have no idea what I did wrong here.

You have set content view after you initialized textView. This should be correct approach:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
TextView tx = (TextView)findViewById(R.id.textView5);
Typeface tf = 
Typeface.createFromAsset(getAssets(),"fonts/myriad_pro_regular.ttf");
tx.setTypeface(tf);

}

At first put your text view initialization under setContentView .

This is working code

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        TextView tx = (TextView)findViewById(R.id.text);
        Typeface tf = Typeface.createFromAsset(getResources().getAssets(),"myriad_pro_regular.ttf");
        tx.setTypeface(tf);

    }

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