Tired to use default font in android application? I m here to learn you, how to use external fonts in your android application. In most of popular application uses their own fonts.It increases the UI layout and make it more attractive !!! So, are you ready to use external fonts???
- First of all create one folder in assets package and name it : fonts
- Insert custom font(s) in fonts folder which you wants to set in your application.
- I have copied three custom fonts for Ex: batman.ttf, harryp.ttf, pac.TTF.
- Add below code in activity_main.xml file.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#222222"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#222222"
android:orientation="horizontal" >
<Button
android:id="@+id/bat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Batman" />
<Button
android:id="@+id/pac"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pac font" />
<Button
android:id="@+id/harry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HarryPotter" />
</LinearLayout>
<TextView
android:id="@+id/ghost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="50dip"
android:gravity="center"
android:text="Font"
android:textColor="#ef0000"
android:textSize="70dip" />
</LinearLayout>
- Now add below code in MainActivity.java file.
MainActivity.java
public class MainActivity extends Activity {
Button bat,pac,harry;
String fontPath;
Typeface tf;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView txtGhost = (TextView) findViewById(R.id.ghost);
bat = (Button)findViewById(R.id.bat);
pac = (Button)findViewById(R.id.pac);
harry = (Button)findViewById(R.id.harry);
bat.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
fontPath = "fonts/batman.ttf";
tf = Typeface.createFromAsset(getAssets(), fontPath);
txtGhost.setTypeface(tf);
}
});
pac.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
fontPath = "fonts/pac.TTF";
tf = Typeface.createFromAsset(getAssets(), fontPath);
txtGhost.setTypeface(tf);
}
});
harry.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
fontPath = "fonts/harryp.ttf";
tf = Typeface.createFromAsset(getAssets(), fontPath);
txtGhost.setTypeface(tf);
}
});
}
}
No comments:
Post a Comment