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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This question already has answers here:
Closed 6 years ago.
回答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.