照例,我們做了一個Demo:
view:
![]() |
打開spinner選取字型 |
![]() |
選擇字型之後,下方會顯示字型名稱以及該樣式。 |
這個方法結合Spinner和從assets獲取資料名稱的動作,完成將選擇的.ttf檔(名稱、屬性)置換到textView之中,我丟了一堆阿哩阿雜的.ttf檔在assets/fonts資料夾中,如果想要測試.ttf的字型,就把檔案丟到assets的fonts資料夾中吧!
而我把使用方法都寫在註釋當中了,以下,這是主要的activity:
package fontTest.susan.idea;
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class FontTestActivity extends Activity {
TextView textView;//顯示字型名稱,字型。
Spinner spinner;//字型的列表
String[] mStringArray;//列表的容器
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.textView);
spinner = (Spinner) findViewById(R.id.spinner);
try {
mStringArray = getAssets().list("fonts");//獲取所有字型的名稱。
//從assets的fonts資料夾中獲取檔案列表。
} catch (IOException e) {
e.printStackTrace();
}
spinner.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, mStringArray));//設定adapter
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
setTypeface(getAssets(),mStringArray[position]);//當選擇了之後進行設定字型
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
setTypeface(getAssets(),mStringArray[0]);
}});
// setTypeface(getAssets(),mStringArray[0]);//不會用到
spinner.setSelection(0);//設定選擇的初始值,該內容會通過OnItemSelectedListener
}
/**設定字型與顯示字型名稱*/
private void setTypeface(AssetManager mAssetManager, String name) {
Typeface face = Typeface
.createFromAsset(mAssetManager, "fonts/" + name);//從assets獲取字型
textView.setTypeface(face);//設定字型
textView.setText(name);//顯示字型名稱
}
}
而layout非常的簡單:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/spinner"
android:layout_centerHorizontal="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
嗯嗯,就是這樣。
沒有留言:
張貼留言
你好,我是小書,如果文章內容有錯誤,或是看到有建議以及任何感想時,歡迎提出分享,我們一起學習一起努力。