20.11.2016 Views

ANDROID APP

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

38 บทที่ 2 การพัฒนาแอพเบื้องต้น: แอคทิวิตี้ และ อินเท็นต์<br />

}<br />

private void startGame() {<br />

Intent launchGame = new Intent(this, PlayGame.class);<br />

startActivity(launchGame);<br />

}<br />

การกำหนด Current Context ใน Anonymous Inner Class<br />

จากชุดคำสั่งที่ 2.8 มีการเรียกใช้แอคทิวิตี้จากการกดปุ่ม ซึ่งในที่นี้เราจะต้องกำหนด Context ให้แก่อินเท็นต์<br />

การใช้คำสั่ง this ในฟังก์ชั่น onClick() อาจจะไม่ชัดเจนนัก สำหรับวิธีต่างๆ ที่ใช้ในการกำหนด Current Context ใน<br />

Anonymous Inner Class มีดังนี้<br />

m ใช้คำสั่ง Context.this แทนคำสั่ง this<br />

m ใช้ getApplicationContext() แทนคำสั่ง this<br />

m ใช้ชื่อของคลาสว่า MenuScreen.this<br />

การเรียกใช้งานฟังก์ชั่นที่มีการกำหนดระดับของ Context อย่างเหมาะสมนั้น จะแสดงอยู่ในชุดคำสั่งที่ 2.8 ในส่วน<br />

ของฟังก์ชั่น startGame()<br />

ในชุดคำสั่งที่ 2.9 แอคทิวิตี้ชื่อ playGame จะประกอบด้วยปุ่มที่มีฟังก์ชั่น onClick() คอย<br />

ตรวจจับการกดปุ่ม ซึ่งจะเรียกใช้งานฟังก์ชั่น finish() เพื่อคืนการทำงานกลับไปสู่แอคทิวิตี้หลัก<br />

และคุณสามารถเพิ่มการทำงานอื่นๆ ลงไปในแอคทิวิตี้นี้ได้<br />

ชุดคำสั่งที่ 2.9 src/com/cookbook/launch_activity/PlayGame.java<br />

package com.cookbook.launch_activity;<br />

import android.app.Activity;<br />

import android.os.Bundle;<br />

import android.view.View;<br />

import android.widget.Button;<br />

public class PlayGame extends Activity {<br />

public void onCreate(Bundle savedInstanceState) {<br />

super.onCreate(savedInstanceState);<br />

setContentView(R.layout.game);<br />

//setup button listener<br />

Button startButton = (Button) findViewById(R.id.end_game);<br />

startButton.setOnClickListener(new View.OnClickListener() {

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!