如何在Android中为特定textview设置字体?

时间:2017-09-01 09:24:06

标签: android

我按照this中的步骤操作,在运行时崩溃了我的应用程序。 以下是我的整个代码。

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);
    }
}

当我添加以下代码时

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

应用程序崩溃,我不知道我在这里做错了什么。

2 个答案:

答案 0 :(得分:2)

初始化textView后,您已设置了内容视图。这应该是正确的方法:

@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);

}

答案 1 :(得分:0)

首先将文字视图初始化置于setContentView

这是正常工作的代码

 @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);

    }