1. 程式人生 > >Android使用typeface實現不同字型的呼叫顯示及String轉換為Unicode

Android使用typeface實現不同字型的呼叫顯示及String轉換為Unicode

 1 package com.example.edittest;
 2 
 3 import android.app.Activity;
 4 import android.graphics.Typeface;
 5 import android.os.Bundle;
 6 import android.view.KeyEvent;
 7 import android.view.View;
 8 import android.view.View.OnClickListener;
 9 import android.widget.Button;
10 import android.widget.EditText;
11 import android.widget.TextView; 12 import android.widget.TextView.OnEditorActionListener; 13 import android.widget.Toast; 14 15 public class MainActivity extends Activity { 16 private EditText editText1; 17 private EditText editText2; 18 @Override 19 protected void onCreate(Bundle savedInstanceState) {
20 super.onCreate(savedInstanceState); 21 setContentView(R.layout.activity_main); 22 initView(); 23 } 24 25 public void initView() { 26 editText1 = (EditText) findViewById(R.id.edit_test1); 27 editText2 = (EditText) findViewById(R.id.edit_test2); 28 29
//呼叫Typeface的createFromAsset方法 這裡用兩個ttf檔案,ziti1.ttf、ziti2.ttf,這裡用的是getAssets()這個方法 30 //字型1 路徑為 assets目錄下建立的fonts資料夾: /assets/fonts/ziti1.ttf 31 Typeface typeface1 = Typeface.createFromAsset(getAssets(), 32 "fonts/ziti1.ttf"); 33 editText1.setTypeface(typeface1); 34 35 // 監聽回車鍵 36 editText1.setOnEditorActionListener(new OnEditorActionListener() { 37 @Override 38 public boolean onEditorAction(TextView v, int actionId, 39 KeyEvent event) { 40 Toast.makeText(MainActivity.this, String.valueOf(actionId), 41 Toast.LENGTH_SHORT).show(); 42 return false; 43 } 44 }); 45 //字型2 路徑為 assets目錄下建立的fonts資料夾: /assets/fonts/ziti2.ttf 46 Typeface typeface2 = Typeface.createFromAsset(getAssets(), 47 "fonts/ziti2.ttf"); 48 editText2.setTypeface(typeface2); 49 50 // 監聽回車鍵 51 editText2.setOnEditorActionListener(new OnEditorActionListener() { 52 @Override 53 public boolean onEditorAction(TextView v, int actionId, 54 KeyEvent event) { 55 Toast.makeText(MainActivity.this, String.valueOf(actionId), 56 Toast.LENGTH_SHORT).show(); 57 return false; 58 } 59 }); 60 61 Button getValue1 = (Button) findViewById(R.id.button1); 62 Button getValue2 = (Button) findViewById(R.id.button2); 63 64 getValue1.setOnClickListener(new OnClickListener() { 65 @Override 66 public void onClick(View v) { 67 //Toast顯示字元轉換的Unicode碼 68 Toast.makeText(MainActivity.this, 69 string2Unicode(editText1.getText().toString()), 70 Toast.LENGTH_SHORT).show(); 71 } 72 }); 73 getValue2.setOnClickListener(new OnClickListener() { 74 @Override 75 public void onClick(View v) { 76 //Toast顯示字元轉換的Unicode碼 77 Toast.makeText(MainActivity.this, 78 string2Unicode(editText2.getText().toString()), 79 Toast.LENGTH_SHORT).show(); 80 } 81 }); 82 } 83 84 // 字串轉換成Unicode 85 public static String string2Unicode(String string) { 86 StringBuffer unicode = new StringBuffer(); 87 for (int i = 0; i < string.length(); i++) { 88 char c = string.charAt(i); 89 unicode.append("\\u" + Integer.toHexString(c)); 90 } 91 return unicode.toString(); 92 } 93 }