วันพุธที่ 1 มกราคม พ.ศ. 2557

2.1 v2 Hello World ภาษาไทย


เวลาผ่านไปปีกว่า กลับมาเริ่มต้นใหม่ด้วย Eclipse รุ่นล่าสุด ณ ธ.ค. 56 ต้องเรียนรู้ใหม่ แม้กระทั่งภาษาไทยใน HelloWorld

ขั้นตอนที่ 1
New Android Project -> เลือกทุกอย่างเป็น  4.2 (API 17) เพราะว่าถึงจะลง 4.4 ไว้ แต่แสดงภาษาไทยไม่ได้

ขั้นตอนที่ 2 สร้าง AVD 4.2  RAM 200

ขั้นตอนที่ 3 สร้างโฟลเดอร์ fonts ไว้ใน assets แล้วไปก๊อบฟอนต์ไทย  .ttf  จาก C:\Windows\Fonts\ มาเก็บไว้ เช่นฟอนต์ TH Mali Grade6.ttf


สังเกตว่า ต้องกำหนด AVD ที่มุมขวาบนให้ run บน API 17 ด้วย และ ค่าของ android:targetSdkVersion="17" ที่ AndroidManifest.xml ก็ต้องเป็น 17

ขั้นตอนที่ 4 แก้ไข / res/values/strings.xml โดยเพิ่มคำภาษาไทยที่ต้องการแสดงเข้าไป

<string name="hello_world">สวัสดี Hello</string>

ขั้นตอนที่ 5 กำหนด android:id เพิ่มใน activity_main.xml จะได้ดังนี้

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtDisplay"
        android:text="@string/hello_world" />

</RelativeLayout>

ขั้นตอนที่ 6 กำหนดการใช้งานฟอนต์ภาษาไทยใน MainActivity.java จะได้ดังนี้

package wasana.example;

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

public class MainActivity extends Activity {

    private TextView txtDisplay;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        txtDisplay = (TextView)findViewById(R.id.txtDisplay);
        Typeface ThaiFont = Typeface.createFromAsset(getAssets(), "fonts/TH Mali Grade6.ttf");
        txtDisplay.setTypeface(ThaiFont);

        txtDisplay.setTextSize(60);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}


ขั้นตอนที่  7 คลิกขวาโปรเจกต์ -> Run as -> Run Configuration -> Target -> เลือก AVD Android 4.2 -> Start - Scale display to real size -> Run


*** อย่างไรก็ดี ถ้าเรา New Project แล้วกำหนดค่าต่างๆ ดังภาพด้านล่าง ก็จะแสดงภาษาไทยได้ทันที ***















ไม่มีความคิดเห็น:

แสดงความคิดเห็น