Custom font in android ( for WHOLE application) [d

2020-03-30 05:09发布

问题:

I have this android code with many classes each with different Views. We can go to settings and change their font according to the font selected. Right now only the pre-installed android fonts are available. Is there a way to slightly tweak my code so that I can add a .ttf file and provide that as an option in fonts. I don't want to make large changes in code.

回答1:

You can use typeface to set custom font for the text in textview. So whenever you required custom font for your textview you can use the below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
    >

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />
<TextView android:id="@+id/text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textColor="#FFF"
          />
 </LinearLayout>

The code:

public class MainActivity extends Activity {

private TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.text);
    Button b= (Button) findViewById(R.id.button1);
    b.setOnClickListener( new OnClickListener()
    {

        @Override
        public void onClick(View v) {
            text.setText("This is a custom toast");
            Typeface typeFace =  Typeface.createFromAsset(getAssets(),"fonts/kn.ttf");
            text.setTypeface(typeFace);

        }

    });

}
}



回答2:

No, you can't, unless you will use your own View with custom font.