我在我创建的assets文件夹中放了一个字体,并在MainActivity中实现了以下代码:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
// Code to change Welcome text to 'BankGothic Bold' font
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "BankGothic Bold.ttf");
TextView myTextview = (TextView)findViewById(R.id.WelcomeTextView);
myTextview.setTypeface(myTypeface);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// Code to display Home Fragment on App Launch Page
HomeFragment homeFragment = new HomeFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(
R.id.relativelayout_for_fragment,
homeFragment,
homeFragment.getTag()
).commit();
}
我也在XML文件中创建了ID,所以很好。
如果我包含此代码,我的应用会在启动时崩溃:
// Code to change Welcome text to 'BankGothic Bold' font
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "BankGothic Bold.ttf");
TextView myTextview = (TextView)findViewById(R.id.WelcomeTextView);
myTextview.setTypeface(myTypeface);
如果我删除它,我的应用程序可以正常使用标准字体。有谁知道为什么?
感谢您的时间。
答案 0 :(得分:0)
检查WelcomeTextView是否在activity_main.xml
中你在另一个xml布局文件中有WelcomeTextView吗?
要更改字体,您应使用书法或创建自定义TextView