0

I'm developing an android app using Java, using which one will be able to enter a text or group of texts using an EditText and once a button is clicked, the font-family of the text should be changed and be displayed in a TextView. The part I'm confused with is, how to change the font-family of a text on a button click. (Everytime I click the font family must change)

Here is the code of my MainActivity.java file

package com.example.fonter;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    EditText mEditText;
    Button changeFontBtn;
    TextView resultTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mEditText = findViewById(R.id.editText);
        changeFontBtn = findViewById(R.id.fontChangeBtn);
        resultTextView = findViewById(R.id.resultView);

        changeFontBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fontChangeFn();
            }
        });
    }

    public void fontChangeFn () {
        if (mEditText.getText().toString().trim().length() > 0) {
            // This is the part I'm confused with.
        }
    }
}

Any help or suggestion would be really appreciated.

Dilip
  • 5
  • 4

1 Answers1

0

You need to add .ttf or .otf font files in assets folder.

Check this question for creating assets folder - Where to place the 'assets' folder in Android Studio?

After creating assets folder, add font file in assets folder.

Add this code for change font:

public void fontChangeFn () {
    if (mEditText.getText().toString().trim().length() > 0) {
        // This is the part I'm confused with.
        Typeface tf= Typeface.createFromAsset(getAssets(), "Poppins-Bold.ttf");
        mEditText.setTypeface(tf);
    }
}

Note: In this code Poppins-Bold.ttf is font name, You can change this according to your requirement.

Android Geek
  • 8,956
  • 2
  • 21
  • 35
  • Thanks a lot buddy! It works. I've pasted some fonts into the assets directory and what I want is everytime I click on the button the font changes. How will I be able to do that? – Dilip Jul 28 '21 at 04:28
  • How many fonts do you have to change? Like you need to change Font A to B then B to C then to N no. of fonts Or Just A to B and B to A. – Android Geek Jul 28 '21 at 04:36
  • it's bad practice to set typeface for each widget, instead create a custom widget – Pankaz Kumar Jul 28 '21 at 06:07
  • @AndroidGeek I need to change from A then to B then to n no. of fonts. But I figured out one thing for it. I'm using a Spinner for it and it does work. Thanks bro. – Dilip Jul 29 '21 at 15:43