简体   繁体   English

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

[英]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.您在初始化 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 .首先将您的文本视图初始化放在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);

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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