android journey

Upload: le-thanh-vu

Post on 03-Jun-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Android Journey

    1/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    1

    ANDROID JOURNEYM U

    Nhng ngy u khm ph Android, nh ln u xa nh ln H Ni hc, lc lng ni qu ngi. Nhiuiu mi m, i lc cn thay i, i lc cm gic thn quen.

    Android c nn vn ha ring. Hu ht mi ngi y u ni ting Java. Nhng bit Java thi thcha , hiu nhng quy tc mi, lnh hi nhng t tng mi cng rt cn thit, l tin gip bntr nn khc bit gia tr n t cht ngi ng ny.

    sng st mnh t ny, bn cn t nht 2 iu:

    Lm vic ! Lm thc s v vic thc t Hiu nhng g bn lm

    Cun sch ny s gip bn c c 2.

    Bn s c dn dt lm 1 vi app Android,qua nhng khi nim v k thut cn thit s c giithiu song song. u kh hiu, s c gii thch va hiu gip bn khi quay cung vi mtng nhng th kh hiu khc.

    Cch tip cn ny gip bn lnh hi kin thc t nhng g bn lm, thay v nhi nht kin thc r i bnt tm cch p dng chng.

    YU C U HNH TRANG

    Tr c tin, hy chc chc r ng bn lnh hi cc khi nim OO v t nht phi thnh tho 1 ngn ng lp trnh OO.

    D th no, hy t chun b cho mnh 1 cun tra cu (references) v 1 cun cng thc nu n(cookbook) v Java.

    C U TRC CUN SCH

    Trong cun sch ny, b n s c tr i nghim cng on xy dng ca 8 Android app.

    2 app u s r t n gin, ch gi gn trong nhng chng u tin. Cc app sau s phc tp hn,apptr i di nht ti 13 chng.

    GeoQuiz Khm ph: Android project, activities, layouts vexplicit intents.

    CriminalIntent Khm ph: Fragments, master-detail interfaces,list-backed interfaces, menus, the camera, implicitintents,

    HelloMoon Khm ph: Fragments, media playback,resources v localization.

  • 8/12/2019 Android Journey

    2/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    2

    NerdLauncher Khm ph: Intent system v tasks.RemoteControl Khm ph: Styles, state list drawables, v cc

    cng c khc to 1 giao din tht hp dn.PhotoGallery 1 Flickr client, ti v trnh din nh t public feed

    ca Flickr.

    Khm ph: Services, multithreading, accessingweb serivces,

    DragAndDraw 1 app v n gin.Khm ph: Handling touch events, creatingcustom view.

    RunTracker Track v hin th 1 bn .Khm ph: Location services, SQLite databases,loaders, maps.

    Table 1: Danh sch cc app Android m b n s c tr i nghi m

    TH THCH

    hu ht mi chng, cui mi bi tp s l phn th thch. l c hi s dng nhng g hcc, tm ti ti liu gii quyt 1 s vn theo cch ca bn.

    FOR THE MORE CURIOUS

    Mi cui chng, l phn For the More Curious. Phn ny gii thch thm hay cung cp thng tin suhn v nhng ch c bn lun trong chng .

    Phn ny c th cha cn thit vi bn, nhng cha th th sao bit ?

    CODE STYLE

    C 3 code style di y s c p dng trong cun sch ny m b n cn lu .

    S dng anonymous inner class cho listeners

    Gip code r rng hn, tuy nhinnn cn nh c trong trng hp cn high performance.

    Sau khi khm ph fragments trong chng 7, chng s c s dng cho t t c UI.

    Nhiu Android developer vn s dng activity-based code, tuy nhin, fragments c nhiu u im hnactivities, bao gm tnh linh hot trong vic xy dng v biu din UI.

    Bi vy hy tp s dng fragments thay th activities.

    Chng ta s vit cc app tng thch v i c thi t b ch y Android phin b n Gingerbread vFroyo.

  • 8/12/2019 Android Journey

    3/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    3

    Android pht hnh cc phin bn mi nh Ice Cream Sandwich, Jelly Bean, Key Lime Pie. Tuy nhinthc t l khong 1 na thit b vn chy phin bn Gingerbread v Froyo.

    Do , chng ta s vit app c kh nng tng thch vi Froyo v t nht l Gingerbread (khong 40%thit b vn chy phin bn ny).

    S kh hn so vi vic vit app tng thch vi cc phin bn mi nht, nhng ng nh i.

    ANDROID VE RSIONS

    Cun sch ny hng ti pht trin app Android c tnh tng thch cao. Khi cun sch ny c vit(bn cha dch), cc app c vit tng thch vi cc phin bn t Android 2.2 (Froyo) ti Android 4.2(Jelly Bean).

    Nhng thay inh hng bi nhng phin bn mi ca Android s c ng trnforums.bignerdranch.com.

    CNG C C N THIT

    CHAPTER 1. YOUR FIRST ANDROID APPLICATION

    Trong chng ny, chng ta s xy dng GeoQuiz, app kim tra kin thc v a l.

    Ngi chi s chn True hay False cho cu h i trn mn hnh v GeoQuiz s phn hi p n.

    http://forums.bignerdranch.com/http://forums.bignerdranch.com/http://forums.bignerdranch.com/
  • 8/12/2019 Android Journey

    4/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    4

    Hnh 1: Giao di n GeoQuiz

    APP BASICS

    GeoQuiz s gm 1 activity v 1 layout:

    1 activity l 1 object ca Activity class, 1 class trong Android SDK. 1 activity chu trch nhimqun l tng tc ngi dng trn 1 UI.

    Chng ta vit 1 subclass ca Activity class thc hin cc chc nng m GeoQuiz cn. 1 appn gin c th ch cn 1 subclass, ph c tp s cn nhiu hn.

    GeoQuiz n gin, nn ch cn 1 subclass tn QuizActivity . QuizActivity s qun l UI hnh1.

    1 layout khai bo 1 b cc i tng UI v v tr ca chng trn mn hnh. Layout c vit di

    nh dng XML.GeoQuiz c 1 layout file tnactivity_quiz.xml . Ni dung XML trong file ny s khai bo UI hnh 1.

  • 8/12/2019 Android Journey

    5/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    5

    Hnh 2: M i quan h gia QuizActivity v activity_quiz.xml

    CREATING AN ANDROID P ROJECT

    to 1 Android project trong Eclipse, chn File New Android Aplication Project.

    Ca s sau xut hin:

    Hnh 3

    Vi Package Name, ta dng reverse DNS convention, gip phn bit vi cc app khc trn thit b vGoogle Play.

    Chn Next ti ca s th 2:

  • 8/12/2019 Android Journey

    6/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    6

    Hnh 4

    B chn Create custom launcher icon, GeoQuiz s s dng launcher icon mc nh.

    Hy chc r ng Create activity c chn.

    Chn Next, n ca s chn kiu activity cn to, ta chn Blank activity:

  • 8/12/2019 Android Journey

    7/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    7

    Hnh 5

    Chn Next.

    Hnh 6

    ca s cui cng ny, ta t tn cho Activity subclass l QuizActivity. Ch hu t Activity, khngyu cu, nhng l convention tt nn p dng.

  • 8/12/2019 Android Journey

    8/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    8

    Layout Name s t ng l activity_quiz, o v tr cc t ca Activity Name, tt c u l ch thng vgia mi t l du gch di. y cng l convention tt nn p dng cho layout cng nh cc resourcekhc.

    Chn Navigation Type l None v Finish.

    Eclipse s to v m project cho bn.

    NAVIGATING IN ECLIPSE

    LAYING OUT THE USER INTERFACE

    Mc nh, Eclipse s m activity_quiz.xml bng Graphical Layout Tool. Tuy nhin, lc ny ta s lm vicvi nh dng XML hiu r hn cch layout hot ng.

    ch nh sa di nh dng XML, ta chn activity_quiz.xml tab pha di editor:

    Hnh 7

    Bn s thy on m XML tng t nh di:

  • 8/12/2019 Android Journey

    9/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    9

    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=".QuizActivity" >

    Ch r ng, activity_quiz.xml khng bt u vi khai bo phin bn v encoding:

    ADT 21, dng ny khng cn c yu cu trong Android layout file. Tuy nhin, bn s vn cn thyn trong vi trng hp.

    Activity layout mc nh khai bo 2 widget: RelativeLayout v TextView .

    Widget l buidingblock m ta dng to nn UI. 1 widget c th hin th vn bn, ha, tng tc viuser, hay t chc cc widget trn mn hnh. Button, text input control, check box u l kiu ca widget.

    Android SDK cung cp nhiu widget, chng u l object ca View class hoc l 1 subclass c a View ( nhTextView hay Button ).

  • 8/12/2019 Android Journey

    10/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    10

    Hnh 8 : RelativeLayout v TextView c khai bo trong activity_quiz.xml s c hi n th trn mn hnh nh th ny

    Nhng, GeoQuiz khng cn nhng widget trn, danh sch di mi l nhng g n cn:

    1 verticalLinearLayout 1 TextView 1 horizontal LinerLayout Hai Button

  • 8/12/2019 Android Journey

    11/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    11

    Hnh 9: Nh ng widget c n thi t c giao di n GeoQuiz mong mu n

    Gi ta s khai bo cc widget mong mun trong activity_quiz.xml. Ta s b phn mu v thm phnmu xanh.

  • 8/12/2019 Android Journey

    12/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    12

    android:orientation="horizontal">

    THE VIEW HIERARCHYMi element, c 1 b attribute. Mi attribute m t 1 cu hnh cho element cha n.

    hiu r cch cc element v attribute ho t ng, ta s m t quan h gia cc widget qua cy phncp.

    Hnh 10

    Root element ca cy phn c p ny l 1 LinearLayout . 1 root element phi khai bo Android resource

    XML namespace l http://schemas.android.com/apk/res/android . LinearLayout tha k t 1 subclass ca View tn ViewGroup . ViewGroup l widget cha v sp xpcc widget khc. Cc subclass khc c a ViewGroup l FrameLayout , TableLayout v RelativeLayout .

    S dng LinearLayout khi bn mun sp xp cc widget n cha theo 1 hng ho c 1 ct.

    Khi 1widget c cha bi 1 ViewGroup , widget c gi l con ca ViewGroup .

    http://schemas.android.com/apk/res/androidhttp://schemas.android.com/apk/res/androidhttp://schemas.android.com/apk/res/androidhttp://schemas.android.com/apk/res/android
  • 8/12/2019 Android Journey

    13/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    13

    LinearLayout , root element, cha 2 con, 1 TextView v 1 LinearLayout khc. LinearLayout con cngcha 2 widget con l 2 Button .

    WIDGET ATTRIBUTESTa s gii thch 1 s attribute m ta dng cu hnh cc widget trn.

    android:layout_width v android:layout_height

    y l 2 attribute gn nh c dng trong hu ht cc kiu widget.

    Gi tr ca chng thng l match_parent hoc wrap_content :

    match_parent view s to nh widget cha ca n wrap_content view s to va vi ni dung n cha fill_parent tng ng vi match_parent , gi tr ny khng c khuyn dng

    Vi root LinearLayout , gi tr ca c width v heightattribute u l match_parent . Mc d n l rootelement, nhng n vn c cha l 1 view m Android cung cp cho app n b tr UI trn y.

    Cc widget khc, widget v height attribute u c gi tr wrap_content . Xem hnh 9 hiu cch nc hin th trn mn hnh.

    TextView ln hn mt cht so vi ni dung n cha l bi android:padding=24pd attribute. Mc ch l cu hi khng qu gn vi 2 Button .

    dp l vit tt ca density-independent , n v ny s c gii thch chng 8.

    android:orientation

    L attribute ca LinearLayout , ch nh cc widget con m LinearLayout cha c sp xp theohng (horizontal) hay theo ct (vertical).

    android:text

    L attribute ca TextView v Button , ch nh vn bn cn hin th trn widget.

    Ch r ng, gi tr ca attribute khng phi literal string, m l tham chiu ti string resource .

    Mt string resource l mt on vn bn nm trong mt XML file ring c gi l strings file .

    Bn c th khai bo gi tr ca android:text l literal string, v d android:text=True . Tuy nhin, cch lm

    ny khng c khuyn dng. Trong chng 15, ta s khm ph cch s dng string resource localization nh th no.

    CREATING STRING RESOURCES Android preject m Eclipse to c sn mt strings file mc nh tn string.xml, trong th mcres/values .

  • 8/12/2019 Android Journey

    14/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    14

    Eclipse cung cp mt giao din cho php ch nh sa string.xml d dng hn, tuy nhin, lc ny hy ch nhsa di nh dng XML hiu cch n hot ng, bng cch chn string.xml tab di editor.

    GeoQuizSettingsHello world!

    Hy b string tn hello_world, bi ta khng cn dng n na v thm nhng string cn thit nh di:

    GeoQuizSettingsHello world!Constantinople is the largest city in Turkey.True False

    Gi th bt c khi no bn t gi tr l @string/false_button cho 1 attribute no , th runtime, gi tr s c thay th bng False .

    Strings file mc nh tn string.xml, nhng bn c th t tn khc nu mun. Bn cng c th c nhiustrings file trong 1 project. Min l strings file nm trong th mc res/values , c resources l rootelement v cha cc string element, th cc string s kh dng trong project.

    PREVIEWING THE LAYOUTGi th hy chc r ng khng cn li hay cnh bo no cn xut hin.

    Bn c th xem trc layout va ch nh sa, activity_quiz.xml, s c hin th nh th no lc runtimebng Graphical Layout Tool.

    Quay li activity_quiz.xml tab pha trn editor, v chn Graphical Layout tab pha di editor.

    Hnh 11: Preview in graphical layout tool (activity_quiz.xml)

  • 8/12/2019 Android Journey

    15/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    15

    FROM LAYOUT XML TO VI EW OBJECTS

    Lm sao nhng element trong activity_quiz.xml tr thnh nhng View object ? Cu tr li nm trongQuizActivity class.

    Khi to GeoQuiz project, mt subclass ca Activity class tn QuizActivity c to, thuc

    com.thenewvu.geoquiz package trong th mc src , ni cha Java code.Hin ti, ni dung ca QuizActivity.java l:

    package com.thenewvu.geoquiz;

    import android.os.Bundle;import android.app.Activity;import android.view.Menu;

    public class QuizActivity extends Activity {

    @Overrideprotected void onCreate(Bundle savedInstanceState) {

    super .onCreate(savedInstanceState);setContentView(R.layout. activity_quiz );

    }

    @Overridepublic boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu. quiz , menu);return true ;

    }

    }

    Hin c 2 phng thc ca Activity c override trong QuizActivity : onCreate(Bundle) vonCreateOptionMenu(Menu)

    B qua onCreateOptionMenu(Menu) , ta s khm ph menu chng 16.

    Phng thc onCreate(Bundle) s c gi khi mt object ca Activity subclass c to. Khi mtactivity c to, n cn mt UI qun l.

    ch nh UI cho activity qun l, ta gi:setContentView(int layoutResourceId);

    Phng thc ny c mt layout v hin th n trn mn hnh. Khi mt layout c c, mi widget trongn c khi to theo cc attribute tr thnh cc View object.

    RESOURCES AND RESOURCE IDSMt layout l mt resource, khng phi l code, m l image file, audio file, XML file.

    Cc resource c nm trong th mc res/ , v d activity_quiz.xml nm trong res/layout/ , string.xml nmtrong res/values/ .

    truy cp resource t code, ta s dng resource ID. V d, resource ID ca activity_quiz.xml lR.layout.activity_quiz .

    c resource ID, trong th mc gen/ , m R.java ta s thy ni dung sau:

  • 8/12/2019 Android Journey

    16/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    16

    /* AUTO-GENERATED FILE. DO NOT MODIFY.** This class was automatically generated by the* aapt tool from the resource data it found. It* should not be modified by hand.*/

    package com.thenewvu.geoquiz;

    public final class R {public static final class attr {

    }public static final class dimen {

    /** Default screen margins, per the Android Design guidelines.

    Customize dimensions originally defined in res/values/dimens.xml (such asscreen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.

    */public static final int activity_horizontal_margin =0x7f040000;public static final int activity_vertical_margin =0x7f040001;

    }public static final class drawable {

    public static final int ic_launcher =0x7f020000;}public static final class id {

    public static final int action_settings =0x7f080000;}public static final class layout {

    public static final int activity_quiz =0x7f030000;}

    }

    R.layout.activity_quiz c khai bo y.

    String cng c resource ID. Ta cha dng resource ID ca mt string no t code, nhng nu c, n s trng th ny:

    setTitle(R.string.app_name);

    Android t sinh resource ID cho mi layout v string, nhng khngt sinh cho mi widget trong layout.

    Khng phi widget no cng cn resource ID, trong chng ny ta ch tng tc vi 2 Button widget t code, vy nn ch chng cn resource ID.

    to mt resource ID cho widget, s dng android:id attribute:

  • 8/12/2019 Android Journey

    17/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    17

    Ch l c du + trong gi tr ca android:id m khng c trong android:text , bi ta ang to 1 resourceID, ch khng tham chiu ti 1 resource ID.

    Luactivity_quiz.xml , v xem li R.java , ta s thy c 2 hng mi xut hin:public static final class id {

    public static final int action_settings =0x7f080002;public static final int false_button=0x7f080001;public static final int true_button=0x7f080000;

    }

    WIRING UP WIDGETS

    Gi th ta c resource ID ca 2 Button , hy dng n trong QuizActivity .

    Trc tin, ta to 2 bin thnh vin.

    public class QuizActivity extends Activity {

    private Button mTrueButton;private Button mFalseButton;

    @Overrideprotected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);setContentView(R.layout. activity_quiz );

    } }

    Ch tin t m trc tn mi bin thnh vin, l Android conventionm ta s dng trong cun schny.

    Sau khi lu QuizActivity.java, ta s nhn c thng bo li: Button cannot be resolved to a type.

    Nguyn nhn l ta cha import android.widget.Button class trong QuizActivity.java, nnButton class b coi l cha c khai bo.

    lm iu , ta thm:

    package com.thenewvu.geoquiz;

    import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.widget.Button;

    public class QuizActivity extends Activity { }

    ORGANIZING IMPORTSVa r i, ta gp li cha import class trong code, vy c tin ch no gip ta vic ny ?

    Eclipse cung cp tin ch trn vi t hp phm: Ctrl + Shift + O

    Tin ch ny ca Eclipse import nhng g bn cn v xa nhng class c import m khng dngtrong code.

  • 8/12/2019 Android Journey

    18/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    18

    GETTING REFERENCES TO WI DGETSTrong mt activity, ly tham chiu ti mt widget, ta gi mt phng thc ca Activity class:

    publi c View findViewById(int id)

    Phng thc ny nhn resource ID ca mt widget v tr v View object ca widget .

    Trong QuizActivity.java, ta ly tham chiu ti True Button v False Button , sau gn vo cc binthnh vin tng ng:

    public class QuizActivity extends Activity {

    private Button mTrueButton;private Button mFalseButton;

    @Overrideprotected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);setContentView(R.layout. activity_quiz );

    this.mTrueButton = (Button)super.findViewById(R.id.true_button);

    this.mFalseButton = (Button)super.findViewById(R.id.false_button);} }

    SETTING LISTENERSMt listener l mt object ang ch 1 event v thc hin mt listener interface cho event .

    Android SDK cung cp mt s listener interface c sn cho mt s event, khng c sn th ta t vit.

    Trong trng hp ny, event m ta mu n listen l khi clickButton , vy listener ca ta phi thc hinView.OnClickListener interface.

    Bt u vi True Button trong QuizActivity.java:

    public class QuizActivity extends Activity {

    private Button mTrueButton;private Button mFalseButton;

    @Overrideprotected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);setContentView(R.layout. activity_quiz );

    this.mTrueButton = (Button)super.findViewById(R.id. true_button );this.mTrueButton.setOnClickListener(new View.OnClickListener() {

    @Overridepublic void onClick(View v) {

    // Does nothing yet, but soon !}

    });

    this.mFalseButton = (Button)super.findViewById(R.id. false_button );}

    }

    USING ANONYMOUS INNER CLASSES

  • 8/12/2019 Android Journey

    19/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    19

    Hy r ng, phn mu xanh c gi l anonymous inner class .

    this . mTrueButton .setOnClickListener( new View.OnClickListener() {

    @Overridepublic void onClick(View v) {

    // Does nothing yet, but soon !}

    });

    Tng t vi False Button :

    this.mFalseButton = (Button)super.findViewById(R.id.false_button);this.mFalseButton.setOnClickListener(new View.OnClickListener() {

    @Overridepublic void onClick(View v) {

    // Does nothing yet, but soon !}

    });

    MAKING TOASTSGi ta mun khi user click mi Button , app s phn hi bng mt pop-up message thng bo kt qu.Pop-up message y c gi l toast .

    Mt toast l mt message ng n thng bo g ti user nhng khng yu cu h nhp hay lm g khc.

    Hnh 12: Minh h a toast

    Trc tin, ta cn thm cc string resource m mu n cc toast hin th.

    Trong string.xml:

  • 8/12/2019 Android Journey

    20/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    20

    GeoQuizSettingsConstantinople is the largest city in Turkey.TrueFalseCorrect !Incorrect !

    to mt toast, ta dng phng thc static ca Toast class:

    publi c static Toast makeText(Con text context, int resId, i nt duration )

    Tham s context thng l mt Activity object (Activity l subclass ca Context class). Tham s resId l resource ID ca string m ta mun toast hin th. Tham s duration thng l mt trong 2 hng m Toast cung cp ch nh toast s hin th trong

    bao lu.

    Sau khi to mt toast, ta gi Toast.show() hin th toast trn mn hnh.

    this.mTrueButton.setOnClickListener(new View.OnClickListener() {

    @Overridepublic void onClick(View v) {

    Toast toast = Toast.makeText( QuizActivity.this ,R.string.correct_toast,Toast.LENGTH_SHORT);

    toast.show();}

    });

    this.mFalseButton.setOnClickListener(new View.OnClickListener() {

    @Overridepublic void onClick(View v) {

    Toast toast = Toast.makeText( QuizActivity.this ,R.string.incorrect_toast,Toast.LENGTH_SHORT);

    toast.show();}

    });

    Ch r ng, sao ta khng ch n gin l nhp this , m phi QuizActivity.this ? L bi ta ang vit codetrong anonymous class , tc this y l View.OnClickListener object.

    RUNNING ON THE EMULATOR

    FOR THE MORE CURIOUS: ANDROID BUILD PROCESS

    Hnh 13 minh ha s lc quy trnh bin dch cc Java code, resource, AndroidManifest.xml (cha meta-data v app) ca GeoQuiz thnh Android Package file (.apk file),nh dng fileci t app trn Android.

  • 8/12/2019 Android Journey

    21/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    21

    Hnh 13 Minh h a quy trnh bin d ch GeoQuiz

    Android Asset Packaging Tool (aapt) bin dch cc layout file v ng chng vo.apk file. runtime,setContentView() c gi trong QuizActivity.onCreate() ch nh layout m QuizActivity s qun l,ni b QuizActivity s dng LayoutInflater class khi to tng View object c khai bo tronglayout file.

  • 8/12/2019 Android Journey

    22/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    22

    Hnh 14 Minh h a quy trnh cc widget c khai bo trong activity_quiz.xml tr thnh cc View object

    THU HO CH

    Di l danh sch nhng kin thc ta hc c trong chng ny:

    Cch to mt Android Application Project trn Eclipse Layout file v cu trc ca n Strings file v cu trc ca n Activity v cch to mt Activity subclass Resource ID, cch to v s dng n trong Java code Listener, Listener Interface v cch s dng Anonymous Inner Class Toast l g v cch to n

    CHAPTER 2. ANDROID AND MODEL-VIEW-CONTROLLER

    Trong chng ny, ta s nng cp GeoQuiz c nhiu cu hi hn.

  • 8/12/2019 Android Journey

    23/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    23

    Hnh 15 Giao di n GeoQuiz v i nhi u cu h i

    thc hin iu ny, ta thm 1 class tn TrueFalse . Mt TrueFalse object s encapsulate m t cu hi.

    Sau , ta s to mt array cc TrueFalse object QuizActivity qun l.

    CREATE A NEW CLASS

    to 1 class mi trong Eclipse, trn Package Explorer, chut phi com.thenewvu.geoquiz package,chn New Class.

    Ta t tn l TrueFalse v tha k t java.lang.Object .

  • 8/12/2019 Android Journey

    24/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    24

    Hnh 16

    Trong TrueFalse class, ta thm 2 bin thnh vin v mt hm to:

    package com.thenewvu.geoquiz;

    public class TrueFalse {private int mQuestionId;private boolean mTrueQuestion;

    public TrueFalse(int questionId, boolean trueQuestion) {this.mQuestionId = questionId;this.mTrueQuestion = trueQuestion;

    }}

    mQuestionId s gi resource ID ca string cu hi. Ta s to cc string cu hi sau.

    mTrueQuestion s ch nh p n ca cu hi.

    Cc bin thnh vin s cn cc getter v setter, nhng thay v g chay, ta s dng tin ch t sinh getter

    v setter ca Eclipse.

    GENERATING GETTERS AND S ETTERSTrc tin, ta cn cu hnh Eclipse n c th:

    Nhn dng tin t m l bin thnh vin

  • 8/12/2019 Android Journey

    25/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    25

    Khi sinh getter cho bin thnh vin kiu boolean, s dng is thay v get

    Trn Eclipse, chn Window Preferences Java Code Style.

    Sau thc hin:

    Thm m l tin t cho bin thnh vin Thm s l tin t cho bin static (ta s s dng trong cc chng sau) Chn Use is prefix for getters that return boolean

    Hnh 17

    Vi cu hnh trn, Eclipse s t sinh getter vi tn getQuestionId() thay v getMQuestionId() ,isTrueQuestion() thay v getTrueQuestion() .

    Tr li TrueFalse.java, chut phi bn trong block ca TrueFalse class, ngay di hm to (ta mun ccgetter v setter s nm y), chn Source Generate Getters And Setters...

    Sau chn mQuestionId v mTrueQuestion :

  • 8/12/2019 Android Journey

    26/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    26

    Hnh 18

    Nhn OK, ta s c:

    package com.thenewvu.geoquiz;

    public class TrueFalse {private int mQuestionId;private boolean mTrueQuestion;

    public TrueFalse(int questionId, boolean trueQuestion) {this.mQuestionId = questionId;this.mTrueQuestion = trueQuestion;

    }

    public int getQuestionId() {return mQuestionId;

    }

    public void setQuestionId(int questionId) {mQuestionId = questionId;

    }

    public boolean isTrueQuestion() {

    return mTrueQuestion;}

    public void setTrueQuestion(boolean trueQuestion) {mTrueQuestion = trueQuestion;

    }}

    Gi th TrueFalse class n r i, ta s thay i QuizActivity n lm vic vi TrueFalse class.Nhng trc tin, hy hiu r cch cc object trong GeoQuiz s lm vic vi nhau:

  • 8/12/2019 Android Journey

    27/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    27

    QuizActivity s qun l 1 array cc TrueFalse object, ng thi tng tc vi layout m n qun l hin th cu hi cng nh phn hi p n.

    Hnh 19

    MODEL-VIEW-CONTROLLER AND ANDROID r ng, hnh 19 minh ha cc object trong GeoQuiz c phn loi thnh 3 layer, Model, Controller vView.

    Model layer, l tp hp ca cc model object. Mt model object, ni chung, l nhng th m app qun l,nh mt user object, mt product object, hay mt photo object, C th GeoQuiz, mt true-falsequestion object.

    View layer, l nhng th bn nhn c trn mn hnh. Ni cch khc, l giao din ca app, c trchnhim biu din d liu v nhn tng tc user.

    Controller layer,ng gia lm trung gian cho Model v View. C th GeoQuiz, Controller hin ti ch c QuizActivity .

    Ch l, cc object trong Model khng bit v v khng giao tip vi View, vngc li. Mi giao tipgia Model v View u qua Controller.

  • 8/12/2019 Android Journey

    28/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    28

    Hnh 20 Dng d liu gi a View, Controller v Model

    BENEFITS OF MVCThu ban u, thi m cc app c vit vi phong cch lp trnh theo cu trc, tht kh thm 1 tnhnng mi bi code cng ngy cng ph c tp, ngp trn bin v hm.

    Thi k tip theo, khi lp trnh hng i tng ra i, cc bin v hm c lin quan mt thit c phnthnh cc class. Li ch r rng l, thay v quay cung vi mt ng bin v hm ln xn, nh pht trinch tp trung vo class gip h gii quyt vn .

    Cng vi tng y, cc class cng ch c nng c phn loi thnh cc layer, v nh pht trin ch tp trung vo layer gip h gii quyt vn .

    Hn na, layer gip gii hn trch nhim cho mi class, gip chng d ti s dng hn.

    V d, TrueFalse class, mt Model class, khng c trch nhim hin th true-false question, bi trchnhim ny thuc v cc View class. Li ch l ta c th s dng TrueFalse class cho nhiu mc chkhc nhau, nh khi ta mun hin th 1 danh sch t t c cu hi, ta c th s dng cng cc object m ta dng hin th tng cu hi.

    UPDATING THE VIEW LAYER

    Gi ta tp trung thay i activity_quiz.xml, mt phn ca View layer.

    Cc task ta cn lm l:

    To resource ID cho TextView Xa android:text attribute ca TextView , bi ta mun thay i text trnTextView ti runtime Thm Next Button

  • 8/12/2019 Android Journey

    29/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    29

    Hnh 21 Cy phn c p cc widget trong activity_quiz.xml sau khi thay i

    Ta thay i activity_quiz.xml nh sau:

    Cc task tip theo l:

    B question_text string, bi ta khng cn dng n na Thm next_button string Thm cc string, l cc cu hi ta mun hin th

    Ta thay i strings.xml nh sau:

    GeoQuizSettingsConstantinople is the largest city in Turkey.

    TrueFalseCorrect !Incorrect !NextThe Pacific Ocean is larger than the Atlantic Ocean.The Suez Canal connects the Red Sea and the Indian Ocean.The source of the Nile River is in Egypt.Lake Baikal is the world\'s oldest and deepest freshwater lake.The Amazon River is the longest river in the Americas.

  • 8/12/2019 Android Journey

    30/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    30

    Oki, View layern r i. Tip theo ta tp trung vo Controller layer.

    UPDATING THE CONTROLLER LAYER

    Controller layer ca GeoQuiz hin ti ch c QuizActivity class.Cc task l:

    Thm 2 bin thnh vin mQuestionTextView v mNextButton gi tham chiu ti TextView vNext Button .

    To array cc TrueFalse object, khi question string v p n cho mi object. Khai bo bin thnh vin mCurrentQuestionIndex lu index ca cu hi ang c hin th, bin

    c gi tr khi khi to l 0, nn cu h i u tin trong mQuestionBank s c hin th khi appkhi ng.

    Trong onClick() trnmNextButton , tng mCurrentQuestionIndex thm 1 v cp nht cu hi trnTextView .

    Ta thay i QuizActivity.java nh sau:

    public class QuizActivity extends Activity {

    private TextView mQuestionTextView;private Button mNextButton;

    private int mCurrentQuestionIndex = 0;private TrueFalse[] mQuestionBank = new TrueFalse[] {

    new TrueFalse(R.string.question_africa, false),new TrueFalse(R.string.question_americas, true),new TrueFalse(R.string.question_asia, true),new TrueFalse(R.string.question_mideast, false),new TrueFalse(R.string.question_oceans, true)

    };

    @Overrideprotected void onCreate(Bundle savedInstanceState) {

    this.mQuestionTextView = (TextView)this.findViewById(R.id.question_text_view);this.mQuestionTextView.setText(this.mQuestionBank[this.mCurrentQuestionIndex].getQuestionId());

    this.mNextButton = (Button)this.findViewById(R.id.next_button);this.mNextButton.setOnClickListener(new View.OnClickListener() {

    @Overridepublic void onClick(View v) {

    QuizActivity quizActivity = QuizActivity.this;quizActivity.mCurrentQuestionIndex ++;quizActivity.mCurrentQuestionIndex %= quizActivity.mQuestionBank.length;int questionStringId = quizActivity.mQuestionBank[quizActivity.mCurrentQuestionIndex].getQuestionId();quizActivity.mQuestionTextView.setText(questionStringId);

    });}

    }

    D nhn ra r ng, ta b trng lp code khi cp nht cu hi trn TextView . Ta s thm 1 private methodtn updateQuestion() thc hin task ny.

    Ta sa li QuizActivity.java nh sau:

    public class QuizActivity extends Activity {

  • 8/12/2019 Android Journey

    31/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    31

    private void updateQuestion() {this.mQuestionTextView.setText(this.mQuestionBank[this.mCurrentQuestionIndex].getQuestionId());

    }

    @Overrideprotected void onCreate(Bundle savedInstanceState) {

    this.mQuestionTextView = (TextView)this.findViewById(R.id. question_text_view );this.mQuestionTextView.setText(this.mQuestionBank[this.mCurrentQuestionIndex].getQuestionId());this.updateQuestion();

    this.mNextButton = (Button)this.findViewById(R.id. next_button );this.mNextButton.setOnClickListener(new View.OnClickListener() {

    @Overridepublic void onClick(View v) {

    QuizActivity quizActivity = QuizActivity.this;quizActivity.mCurrentQuestionIndex ++;quizActivity.mCurrentQuesti onIndex %= quizActivity.mQuestionBank.leng th;int questionStringId =

    quizActivity.mQuestionBank[quizActivity.mCurrentQuestionIndex].getQuestionId();quizActivity.mQuestionTextView.setText(questionStringId);quizActivity.updateQuestion();

    }});

    }

    }

    Tip theo, ta thm private method tn checkAnswer(boolean) kim tra user tr li ng hay sai va ra thng bo:

    public class QuizActivity extends Activity {

    private void checkAnswer(boolean userAnwser) {boolean correctAnwser = this.mQuestionBank[this.mCurrentQuestionIndex].isTrueQuestion();

    int messageResId = 0;if(userAnwser == correctAnwser) {

    messageResId = R.string. correct_toast ;} else {messageResId = R.string. incorrect_toast ;

    }

    Toast. makeText (this, messageResId, Toast. LENGTH_SHORT ).show();}

    @Overrideprotected void onCreate(Bundle savedInstanceState) {

    this.mTrueButton = (Button)this.findViewById(R.id. true_button );this.mTrueButton.setOnClickListener(new View.OnClickListener() {

    @Overridepublic void onClick(View v) {

    Toast toast = Toast. makeText (QuizActivity.this,R.string. correct_toast ,Toast. LENGTH_SHORT );

    toast.show();QuizActivity.this.checkAnswer(true);

    }});

    this.mFalseButton = (Button)this.findViewById(R.id. false_button );this.mFalseButton.setOnClickListener(new View.OnClickListener() {

    @Overridepublic void onClick(View v) {

    Toast toast = Toast. makeText (QuizActivity.this,R.string. incorrect_toast ,Toast. LENGTH_SHORT );

    toast.show();QuizActivity.this.checkAnswer(false);

    }});

  • 8/12/2019 Android Journey

    32/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    32

    }

    RUNNING ON A DEVICE

    ADDING AN ICON

    Task tip theo ca ta l thm 1 icon cho Next Button .

    Trc tin, ta cn ti: http://www.bignerdranch.com/solutions/AndroidProgramming.zip

    y l cc solution file ca cun Android Programming The Big Nerd Ranch Guide 1 st .

    Gii nn v m th mc 02_MVC/GeoQuiz/res , trong th mc ny, m 3 th mc khc, drawable-hdpi ,drawable-mdpi v drawable-xhdpi .

    Hu t trong tn 3 th mc trn ch nh screen pixel desity ca 1 device: Mdpi Medium density screens (~160 dpi) Hdpi Hight density screens (~240 dpi) Xhdpi Extra high density screens (~320 dpi)

    (Cng c ldpi Low density screens, nhng cc device vi ldpi gi lc hu)

    Trong mi 3 th mc trn, c 2 image file: arrow_right.png v arrow_left.png . Cc file ny c ch nh ph hp vi screen pixel density mi th mc, gip chng c hin th tt nht trn cc device cscreen pixel density tng ng.

    ADDING RESOURCES TO PROJECTTip theo ta s thm cc image file trn vo GeoQuiz project.

    Copy cc image file mi 3 th mc trn vo tng ng 3 th mc trong res/ ca GeoQuiz project.

    Kt qu, ta s c:

    http://www.bignerdranch.com/solutions/AndroidProgramming.ziphttp://www.bignerdranch.com/solutions/AndroidProgramming.ziphttp://www.bignerdranch.com/solutions/AndroidProgramming.ziphttp://www.bignerdranch.com/solutions/AndroidProgramming.zip
  • 8/12/2019 Android Journey

    33/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    33

    Hnh 22

    Ch r ng, nu ta dng cch drag and drop, ta s gp ca s di, hy chn Copy files thay v Link tofiles:

    Hnh 23

    Mi .png, .jpg hay .gif file m ta thm vo th mc res/drawable_... s t ng c gn 1 resource ID.Nhng ch , tn file phi l ch thng v khng c khong tr ng.

    Kim chng, hy m gen/R.java , ta s thy r ng c 2 resource ID mi c khai bo trong R.drawable :R.drawable.arrow_left v R.drawable.arrow_right .

    D nhn ra l, ta thm 2 image file cho mi screen pixel density (tng l 6), nhng ti sao ch c 2resource ID ? L bi ta khng cn xc nh screen pixel density ca device ti runtime, ta ch cn s dng 2 resource ID trn, cn Android s lo phn chn image file hp l hin th cho mi device.

  • 8/12/2019 Android Journey

    34/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    34

    REFERENCING RESOURCES IN XMLTa s s dng 1 trong 2 resource ID trn trong activity_quiz.xml to 1 icon cho Next Button :

  • 8/12/2019 Android Journey

    35/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    35

    @Overridepublic void onClick(View v) {

    QuizActivity.this.nextQuestion();}

    });

    this.mNextButton = (Button)this.findViewById(R.id. next_button );this.mNextButton.setOnClickListener(new View.OnClickListener() {

    @Overridepublic void onClick(View v) {

    QuizActivity quizActivity = QuizActivity.this;

    quizActivity.mCurrentQuestionIndex ++;quizActivity.mCurrentQuesti onIndex %= quizActivity. mQuestionBank.length;int questionStringId =

    quizActivity.mQuestionBank[quizActivity.mCurrentQuestionIndex].getQuestionId();quizActivity.mQuestionTextView.setText(questionStringId);quizActivity.updateQuestion();QuizActivity.this.nextQuestion();

    }});

    }

    }

    CHALLENGE: ADD A PREVIOUS BUTTON

    Th thch ln ny l thm 1 Previous Button, c kh nng hin th cu hi trc cu hi hin ti.

    Hnh 24

    Trc tin, ta t p trung vo View layer.

    Ta thay i activity_quiz.xml nh sau:

  • 8/12/2019 Android Journey

    36/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    36

    Thay i strings.xml nh sau:

    GeoQuizSettingsConstantinople is the largest city in Turkey.

    TrueFalseCorrect !Incorrect !NextPrevThe Pacific Ocean is larger than the Atlantic Ocean.The Suez Canal connects the Red Sea and the Indian Ocean.The source of the Nile River is in Egypt.Lake Baikal is the world\'s oldest and deepest freshwater lake.The Amazon River is the longest river in the Americas.

    Gi ta t p trung vo Controller layer.

    Ta thay i QuizActivity.java nh sau:

    public class QuizActivity extends Activity {

    private TextView mQuestionTextView;private Button mNextButton;private Button mPreviousButton;

    private void nextQuestion() {this .mCurrentQuestionIndex++;this .mCurrentQuestionIndex %= this .mQuestionBank.length;this .updateQuestion();

    }

    private void previousQuestion() {this.mCurrentQuestionIndex--;if (this.mCurrentQuestionIndex == -1) {

    this.mCurrentQuestionIndex += this.mQuestionBank.length;

  • 8/12/2019 Android Journey

    37/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    37

    }this.updateQuestion();

    }

    @Overrideprotected void onCreate(Bundle savedInstanceState) {

    this .mNextButton = (Button) this .findViewById(R.id. next_button );

    this .mNextButton.setOnClickListener( new View.OnClickListener() {@Overridepublic void onClick(View v) {

    QuizActivity. this .nextQuestion();}

    });

    this.mPreviousButton = (Button) this.findViewById(R.id. previous_button );this.mPreviousButton.setOnClickListener(new View.OnClickListener() {

    @Overridepublic void onClick(View v) {

    QuizActivity.this.previousQuestion();}

    });}

    }

    CHALLENGE: FROM BUTTON TO IMAGEBUTTONGiao din ca GeoQuiz s trng gn gng hn nu Next v Previous Button ch hin th icon, nh th ny:

    Hnh 25

    lm c iu ny, ta s s dng ImageButton widget thay vButton widget.

  • 8/12/2019 Android Journey

    38/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    38

    Hnh 26 Quan h th a k ca ImageButton v Buton

    Trc tin, t p trung vo View layer.

    Ta s thay i activity_quiz.xml nh sau:

  • 8/12/2019 Android Journey

    39/39

    A n d r o i d J o u r n e y c a L Thanh V ( @thenewvu )

    chng ny, ta khm ph thm:

    Cch to 1 class mi trong Eclipse Cch s dng tin ch t sinh getter v setter trong Eclipse Model-View-Controller trong pht trin Android Application Cch thm resource m i vo project trong Eclipse Cc loi screen pixel density (dpi)