0
votes

I put a font in the assets folder I created and have implemented the following code in my 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();
    }

I have created the ID in the XML file too so that is fine.

If I include this code my app crashes on launch:

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

If I remove it my app works fine with the standard font. Does anyone know why?

Thanks for your time.

1
change name of font file to something without space and and all in lowercase, then use this name in your code.Akram
Tried using 'bankgothic.ttf' but sadly didn't work. Thanks for the suggestion though.user9169562
can you post the logcat error when you run app and it crashes?Akram
Ah yes, I didnt think of looking at that. Give me a moment plsuser9169562
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object referenceuser9169562

1 Answers

0
votes

Check whether WelcomeTextView is in activity_main.xml

Do you have WelcomeTextView in another xml layout file?

To change font you should use Calligraphy or create a custom TextView