2011年7月20日星期三

動態改變文字的字體, setTypeface(typeface, style)

我們可以使用 Java 碼, 調用 setTypeface() 方法, 改變文字的字體.

textview.setTypeface(typeface, style)

其中 typeface 參數可以是:
- Typeface.DEFAULT
- Typeface.DEFAULT_BOLD
- Typeface.MONOSPACE
- Typeface.SANS_SERIF
- Typeface.SERIF

style 參數可以是:
- Typeface.BOLD
- Typeface.BOLD_ITALIC
- Typeface.ITALIC
- Typeface.NORMAL

實例:

動態改變文字的字體, setTypeface(typeface, style)

package com.AndroidText;

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

public class AndroidTextActivity extends Activity {

TextView text;
Button buttonChangeTypeFace;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.text);
buttonChangeTypeFace = (Button)findViewById(R.id.changetypeface);

buttonChangeTypeFace.setOnClickListener(new Button.OnClickListener(){

public void onClick(View arg0) {
// TODO Auto-generated method stub

/*
* setTypeface(typeface, style)
* typeface:
* - Typeface.DEFAULT
* - Typeface.DEFAULT_BOLD
* - Typeface.MONOSPACE
* - Typeface.SANS_SERIF
* - Typeface.SERIF
*
* style:
* - Typeface.BOLD
* - Typeface.BOLD_ITALIC
* - Typeface.ITALIC
* - Typeface.NORMAL
*/


//setTypeface for TextView
text.setTypeface(Typeface.MONOSPACE, Typeface.BOLD);
//setTypeface for Button
buttonChangeTypeFace.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
}});
}
}


<?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"
>
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/changetypeface"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Change Typeface"
/>
</LinearLayout>


沒有留言:

發佈留言