Phan_02_Giao_dien_nguoi_dung.pdf

Embed Size (px)

Citation preview

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    1/94

    Pht trin ngdng

    SmartphoneTi liu lu hnh ni b y l ti liu tham kho sdng trong mn hc Lp trnh ng dng SmartphoneAndroid

    c tng hp, bin son tnhiu ngun bi cc thnh vin ca Nhm nghin cu v ng dng cngnghA106-i hc Hoa Sen.

    Nhm A106-http://profiles.hoasen.edu.vn/groups/584/

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    2/94

    Pht trin ng dng SmartphoneAndroid

    1

    Pht trin ngdng Smartphone

    Phn 02: Giao din ngi dngL c HuyEmail: [email protected]

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    3/94

    Pht trin ng dng SmartphoneAndroid

    2

    Mc lc

    1 ViewGroup .............................................................................................................. 4

    1.1 LinearLayout .................................................................................................... 5

    1.2 AbsoluteLayout .............................................................................................. 12

    1.3 TableLayout ................................................................................................... 14

    1.4 RelativeLayout ............................................................................................... 16

    1.5 FrameLayout .................................................................................................. 19

    1.6 ScrollView ...................................................................................................... 21

    2 View ...................................................................................................................... 24

    2.1 Basic Views ................................................................................................... 24

    2.1.1 ProgressBar View ...................................................................................... 35

    2.1.2 AutoComplete TextView ............................................................................ 42

    2.2 PickerView ..................................................................................................... 46

    2.2.1 TimePicker ................................................................................................. 46

    2.2.2 DatePicker ................................................................................................. 50

    2.2.3 List Views................................................................................................... 54

    2.2.4 Spinner View .............................................................................................. 57

    2.3 Display Views ................................................................................................ 62

    2.3.1 Gallery and ImageView .............................................................................. 62

    2.3.2 ImageSwitcher ........................................................................................... 69

    2.3.3 GridView .................................................................................................... 74

    2.4 Menus ............................................................................................................ 77

    2.5 Additional View .............................................................................................. 87

    2.5.1 AnalogClock v DigitalClock ...................................................................... 87

    2.5.2 WebView.................................................................................................... 89

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    4/94

    Pht trin ng dng SmartphoneAndroid

    3

    Ti thi im ny, bn c ththy rng thnh phn c bn ca mt ng dng android chnh lActivity. Activityl thnh phn ti qun trng c bt k mt ng dng ndroid no Thut ng

    ctivity ch mt vic m ngi dng c th thc hin trong mt ng dng ndroid Do gn nh mictivity u tng tc vi ngi dng nn lp ctivity m nhn vic to r mt c s window ngi lp trnh t ln mt giao din ngi dng bng phng thc setContentView(View). Ta cthxem Activity l mt ca sng dng. Mt ctivity c th mng nhiu dng khc nhu mt c ston mn hnh (full screen window), mt c s floting vi windowsIsFloting hy nm lng bntrong mt ctivity khc vi ActivityGroup). Ca sng dng m Activity to ra c thcha ccwidgetsnh button, lble, text boxex Thng thng, xy dng giao din ngi dng ta sdngfile xml trong forder res/lyout nh ngh cc i tng ha mun thhin ln giao din ngidng cng vi cc thuc tnh tng ng quyt nh cch thc thhin i tng h trn ca sng dng Di y l mt v dfile xml nh ngh cc i tng ha thhin giao din ngi

    dng ca ng dng:

    Khi chng trnh thc thi, giao din h c np tfile xml trong phng thc onCreate()bng cch sdng phng thc setContentView()ca Activitychnh file xml mong mun.

    V d:

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {

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

    }

    Khi m code c chng trnh c bin dch, mi phn ttrong file xml c bin dch thnhnhng i tng h tng ng cng vi cc thuc tnh c cung cp km theo cc phn ttrongthxml ndroid su s to ra cc thhin c cc i tng h ngi dng cung cp choctivity khi n c np.

    Vic xy dng mt giao din ngi dng bng cch sdng file xml rt n gin, tuy nhin stn rt nhiu thi gian nu nh lp trnh cn phi xy dng giao din h ngi dng mt cc linh

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    5/94

    Pht trin ng dng SmartphoneAndroid

    4

    hot trong lc thc thi (V d: Khi xy dng game). Tuy nhin cc nh pht trin ng dng vn c thxy dng giao din h ngi dng bng cch sdng cu lnh.

    Views and ViewGroups

    Mt Activitych cc i tng Viewv cc i tng ViewGroup. Mt i tng View lmt i tng hodng hin thni dung ln mn hnh. V d: Button, lblel, text boxes MtViewc dn sut tcc class: android.view.View.Mt hoc nhiu View c thc nhm li cngnhau bn trong mt ViewGroup. Mt ViewGroupcung cp khnng cho phpbtr cc i tng hocha trong n mt cch ph hp. C thsdng cc ViewGroup btrcc i tng hotheo dng, theo ct, theo dng bng hay theo schnh tocth. Mi ViewGroup c dn xuttclass android.view.ViewGroup. Android htrcc ViewGroupsu y

    LinearLayout

    AbsoluteLayout

    TableLayout

    RelativeLayout

    FrameLayout

    ScrollView

    Di y l chui cc bi hc sni r vtng loi ViewGroupmt cch chi tit hn Ch rng, trong cc bi thc hnh di y thng xuyn lng cc loi ViewGroupvi nhu xy dngmt giao din ngi dng.

    1 ViewGroup

    To 1 Project n gin

    Trong hng dn ny, chng ta sto mt project android vi cc thng snh su

    Project name: UIExample

    Build target: Android 2.3.3.

    Application name: UI Example

    Package name: android.uiexample

    Create Activity: main

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    6/94

    Pht trin ng dng SmartphoneAndroid

    5

    1.1 LinearLayout

    LinearLayoutl loi ViewGroup cho php sp xp cc i tng View(cha trong n) trongmt ct n hy mt hng n thy cch mt LinearLauoutlm vic nh thno, hy bsung

    vo file main.xml trong forder lyout nh su

    Trong file main.xmlny, ta quan st thy rng phn tgc l v n c chamt thnh phn . Phn tsxc nh cch hin thca cc i tngView cha trong n thng qua cc thuc tnh.

    Viewv ViewGroupc mt tp cc thuc tnh rt hay sdng c lit k qua bng sau:

    Thuc tnh c t

    layout_width Xc nh chiu rng ca mt View hoc ViewGroup

    layout_height Xc nh chiu cao ca mt View hoc ViewGroup

    layout_marginTop Xc nh phn mrng pha bn trn ca View hoc ViewGroup

    layout_marginBottom Xc nh phn mrng ph bn di ca View hoc ViewGroup

    layout_marginLeft Xc nh phn mrng pha bn tri ca View hoc ViewGroup

    layout_marginRight Xc nh phn mrng pha bn phi ca View hoc ViewGroup

    layout_gravity Xc nh cch t cc i tng View con

    layout_weight Xc nh phn kch thc thhin ca View hoc ViewGroup (Sdngvi thuc tnh layout_width hoc lyout_height c gn gi trfill_parentwrap_content hoc gi trcnh: 100px)

    layout_x Xc nh tox ca the View hoc ViewGroup

    layout_y Xc nh toy ca the View hoc ViewGroup

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    7/94

    Pht trin ng dng SmartphoneAndroid

    6

    Ch rng mt vi cc thuc tnh trn chc sdng khi mt View c nh ngh r rngtrong mt ViewGroup cth.

    V d:

    - Hai thuc tnh layout_weight v layout_gravity ch c s dng nu View nm trongLinearLayout hoc l trong TableLayout.

    Xem xt phn code xml sau:

    - Phn t TextView trn c chiu rng bng vi chiu rng ca phn t cha ca n

    (fill_parent- Trong trng hp ny n bng vi chiu rng mn hnh). Chiu cao trong

    trng hp ny, khi bn khai bo l wrap_contentth chiu cao ca n sl chiu cao cnthit m ni dng ca TextViewdng hin thon text.

    Cn trong trng hp di y, chiu rng ca TextView c t l 105 pixels.

    Khi phn code giao din trn c np ln Activity sc giao din nh su:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    8/94

    Pht trin ng dng SmartphoneAndroid

    7

    Mc nh ca LinearLayout s sp xp cc i tng ho (View) trong n theo chiungang, nu bn mun thy i n thnh chiu dc bn c thsa phn code phn tgc LinearLayoutli nh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    9/94

    Pht trin ng dng SmartphoneAndroid

    8

    Bng cch thy i thuc tnh android:orientation=vertical t thy i cchLinearLayoutsp xp cc i tng hobn trong n. Thuc tnh android:orientationc thgnhai gi trtng ng sau:

    - vertical Dng xc nh cc i tng hocha trong LinearLayout c sp xptheo chiu dc.

    - horizontal Dng xc nh cc i tng ho cha trong LinearLayout c spxp theo chiu ngang.

    Gi trca thuc tnh kch thc mt i tng hotrong ndroid c phn thnh hai loi:

    - Gi trcnh Xc nh cthgi trkch thc. V d: 150px).

    - Gi trlinh hot. Gi trny phthuc vo mt trong hai yu t:

    o Ni dung m mt i tng homun hin th.Vi View th ni dung ny l ontext, Vi ViewGroup l cc phn tcon m n cha.

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    10/94

    Pht trin ng dng SmartphoneAndroid

    9

    o Phn khng gin m i tng cha cn trng.

    Trong LinearLayoutbn c thp dng cc thuc tnh layout_weightv layout_gravitynhsau:

    Hnh sau shin thButtonc gn vo bn phi ca phn tcha c n Trong trng hpny l LinearLayout) sdng thuc tnh layout_gravity, v sdng thuc tnh layout_weightchocc Button, EditText(tng gi trca layout_weightbng 1). Sau khi np phn giao din trn voActivity ta sc giao din nh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    11/94

    Pht trin ng dng SmartphoneAndroid

    10

    Phn tch phn giao din bn trn ta sthy rng:

    - Thgc ca ton bgiao din l LinearLayout vi hai thuc tnhandroid:layout_width=fill_parentv android:layout_height=fill_parentxc nhchiu rng v chiu cao LinearLayoutschim ton chiu rng v chiu cao c i tngch n Nhng do thLinearLayoutny l thgc (Thngoi cng) nn n sc tln mn hnh in thoi khi ng dng c mln. V vy n schim ton bchiu rngv chiu cao c mn hnh in thoi y l mt trng hp gi trkch thc ca mt itng hol linh hot v phthuc vo khng gian cn trng c i tng cha (Trongtrng hp ny i tng ch l mn hnh in thoi, do ch cha g ht nn n c xem

    l rng).- ThTextViewc thuc tnhandroid:layout_width="fill_parent" v

    android:layout_height=wrap_contentxc nh knh thc chiu ngang ca TextViewschim ton bkhong trng cn li i tng cha n (LinearLayout), v chiu cao caTextViewsphthuc vo ni dung n cn hin th(TextViewchim mt khong chiucao bng vi chiu cao cn hin thon text m n ng gi).

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    12/94

    Pht trin ng dng SmartphoneAndroid

    11

    - ThButtonc thuc tnh android:layout_width=100pxxc nh kch thc chiu rngca n l 100px y l mt trng hp m gi trkch thc ca mt i tng holcnh (Chiu rng = 100px).

    - ThButton c thuc tnh android:layout_gravity="right"xc nh rng i tng Buttonkhi c np ln giao din scanh lbn phi so vi i tng cha n.

    Bng sau lit k cc gi trc thgn cho thuc tnh android:layout_gravity:

    Gi tr M t

    top t i tng ho ln nh trn cng c ViewGroup ch n Thuc tnhny khng thy i gi tr kch thc.

    bottom t i tng ho xung di cng c ViewGroup ch n Thuc tnhny khng thy i gi tr kch thc.

    left t i tng ho bn tri c ViewGroup ch n Thuc tnh ny khngthy i gi tr kch thc.

    right t i tng ho bn phi c ViewGroup ch n Thuc tnh ny khngthy i gi tr kch thc.

    center_vertical t i tng ho cnh gi theo chiu dc c ViewGroup ch n Thuctnh ny khng thy i gi tr kch thc.

    fill_vertical Tng kch thc c c i tng ho trn y chiu co ViewGroup chn.

    center_horizontal t i tng ho cnh gi theo chiu ngng c ViewGroup ch nThuc tnh ny khng thy i gi tr kch thc.

    fill_horizontal Tng kch thc c c i tng ho trn y chiu rng ViewGroupch n

    center t i tng ho chnh gic ViewGroup ch n Thuc tnh nykhng thy i gi tr kch thc.

    fill Tng kch thc c c i tng ho trn y kch thcViewGroupch n

    clip_vertical Additional option that can be set to have the top and/or bottom edges of thechild clipped to its container's bounds. The clip will be based on the verticalgravity: a top gravity will clip the bottom edge, a bottom gravity will clip thetop edge, and neither will clip both edges.

    clip_horizontal Additional option that can be set to have the left and/or right edges of the childclipped to its container's bounds. The clip will be based on the horizontalgravity: a left gravity will clip the right edge, a right gravity

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    13/94

    Pht trin ng dng SmartphoneAndroid

    12

    Lu Thuc tnh android:layout_gravity c thgn nhiu hn mt thuc tnh.

    VD: android:layout_gravity:top|left

    Chai thButtonv EditTextu c thuc tnh android:layout_height=wrap_contentv

    android:layout_weightvi cc gi trtng ng: Button: 0.2 EditText: 0.8.Nu thuc tnh kchthc ca mt i tng ho(android:layout_heightv android:layout_width) xc nh lwrap_contentth kch thc ny sv hin thni dung ca n (Vi View th ni dung ny lon text, Vi ViewGroup l cc phn tcon m n cha). Tuy nhin nu sdng thm thuc tnhandroid:layout_weight th kch thc c cc i tng hony sphthuc vo gi trca thuctnh ny.gii thch vcch sdng thuc tnh android:layout_weightta xem xt li v dtrn nhsau:

    - Ta c mt thgc LinearLayoutch b i tng TextView, Button, EditText. Cbai tng ny c sp xp theo chiu dc ttrn xung.

    - Chiu cao ca TextViewl wrap_contentngh l n sc mt cao v hin thmt on text cnh Hello ndroid-Ta sbn vkhi nim @string/hello phn sauca gio trnh).

    - Su khi xc nh c chiu cao ca TextViewth ta scn li mt khong trng dng sp xp Buttonv EditText. Ta gi khong trng ny l H. Chiu cao c hi i tngny l wrap_content v gi trandroid:layout_weightln lt l 0.2 v 0.8.Lc nychiu cao ca Buttonsl 0.2*H v chiu cao ca EditTextl 0.8*H.

    Ta cn lu rng tng android:layout_weightc cc i tng trong cng mtViewGrouplun l 1.0 (android:layout_weightca Button+ android:layout_weightcaEditText=1.0)

    1.2 AbsoluteLayout

    AbsoluteLayoutcho bn chnh chnh xc vtr ca cc thnh phn con, xem xt v dsau:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    14/94

    Pht trin ng dng SmartphoneAndroid

    13

    android:layout_width="113px"android:layout_height="wrap_content"android:text="Button"android:layout_x="12px"

    android:layout_y="361px"/>

    Khi np phn code xml trn ln Activity th ta sc giao din nh su

    v dtrn xut hin thm hai thuc tnh l:

    - android:layout_x: Xc nh tox c i tng trong toOxy.- android:layout_y Xc nh tox c i tng trong toOxy.

    Lu Gc toc xc nh c xc nh l im trn cng gc tri ca ViewGroupgnnht cha n.

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    15/94

    Pht trin ng dng SmartphoneAndroid

    14

    1.3 TableLayout

    TableLayout dng tchc cc i tng Viewdi dng mt bng gm nhiu hng, nhiuct. Mi dng c thhin bng mt th Trong mi dng c thcha mt hoc

    nhiu i tng View. Mi i tng View t trn mt dng sto thnh mt trong giao din bngdo TableLayout to ra. Chiu rng ca mi ct c xc nh bng chiu rng ln nht ca cc nmtrn cng mt ct.

    V d:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    16/94

    Pht trin ng dng SmartphoneAndroid

    15

    Khi np phn code xml trn ln Activity th ta sc giao din nh su

    v dtrn, giao din hoc tchc di dng mt bng gm c bn dng vi hai ct. ngy di cha TextViewPassword c mt thrng. Nu khng t thny, thCheckBoxRemember Password sxut hin ngy bn di TextViewPssword nh hnh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    17/94

    Pht trin ng dng SmartphoneAndroid

    16

    1.4 RelativeLayout

    RelativeLayoutcho php bn chnh mi quan hgia cc i tng View/ViewGroup. Taxt v dsau:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    18/94

    Pht trin ng dng SmartphoneAndroid

    17

    />

    Ch rng mi View c nhng bn trong RelateLayoutc cc thuc tnh cho php xc nhmi quan hgia chng vi RelativeLayout cha n hoc cc View, ViewGroup khc. Mt s thuctnh nh l

    - layout_alignParentTop:Thuc tnh ny c hai gi trtrue/false. Nu l true th i tnghony snm st trn cng ca RelativeLayout cha n.

    - layout_alignParentBottom: Thuc tnh ny c hai gi tr true/false. Nu l true th itng hony snm st di cng ca RelativeLayout cha n.

    - layout_alignParentLeft:Thuc tnh ny c hai gi trtrue/false. Nu l true th i tng

    hony snm st bn tri ca RelativeLayout cha n.- layout_alignParentRight: Thuc tnh ny c hai gi trtrue/false. Nu l true th i tng

    hony snm st bn phi ca RelativeLayout cha n.

    - layout_alignLeft:Thuc tnh ny xc nh id c i tng View hoc ViewGroup m nsnm bn tri c i tng

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    19/94

    Pht trin ng dng SmartphoneAndroid

    18

    - layout_alignRight:Thuc tnh ny xc nh id c i tng View hoc ViewGroup m nsnm bn phi c i tng

    - layout_below:Thuc tnh ny xc nh id c i tng View hoc ViewGroup m n s

    nm bn di c i tng - layout_above:Thuc tnh ny xc nh id c i tng View hoc ViewGroup m n s

    nm bn trn i tng

    - layout_centerInParent: Thuc tnh ny c hai gi trtrue/false. Nu l true th i tnghony snm chnh gia ca RelativeLayout cha n.

    - layout_centerHorizontal:Thuc tnh ny c hai gi trtrue/false. Nu l true th i tnghony scanh gia theo chiu ngang so vi RelativeLayout cha n.

    - layout_centerVertical: Thuc tnh ny c hai gi trtrue/false. Nu l true th i tng

    hony scanh gia theo chiu dc so vi RelativeLayout cha n.Khi np phn code xml trn ln Activity th ta sc giao din nh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    20/94

    Pht trin ng dng SmartphoneAndroid

    19

    1.5 FrameLayout

    FrameLayoutl ViewGroup c bit c thsdng hin thmt View n Tt ccc itng View c t trong FrameLayout slun trn cng bn tri ca FrameLayout.

    Xem xt on code xml sau:

    y t c mt FrameLayout bn trong mt AbsoluteLayout. Bn trong FrameLayout, bn

    nhng mt ImageView. Sau khi np phn code xml trn ln Activity bn sc giao din nh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    21/94

    Pht trin ng dng SmartphoneAndroid

    20

    Nu ta thm mt View khc (Mt Button) bn trong FrameLayout, View mi thm v snm ln View trc :

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    22/94

    Pht trin ng dng SmartphoneAndroid

    21

    />

    Sau khi np ln Activity ta sc giao din nh su

    Bn c ththm nhiu View vo FrmeLyout, nhng mi view schng ln nh ca Viewtrc v nm st gc trn cng bn tri ca FrameLayout cha n.

    1.6 ScrollView

    Mt ScrollView l mt trng hp c bit ca FrameLayout, n cho php ngi s dngcun qua mt dnh sch cc i tng View hoc ViewGroup chim gikhng gian hin thln hnso vi mn hnh in thoi h tr. ScrollView ch c th cha duy nht mt i tng View hocViewGroup Thng l LinearLayout).

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    23/94

    Pht trin ng dng SmartphoneAndroid

    22

    Ch : Khng sdng ListViewcng vi ScrollView. ListViewc thit khin thmtdanh sch cc i tng c lin hvi nhu VD Dnh sch contct v c ti u ho ph hpvi nhng danh sch ln.

    V dsau minh ha ScrollViewcha mt LinearLayout:Thc thi on code trn bn sc kt qunh sau:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    24/94

    Pht trin ng dng SmartphoneAndroid

    23

    android:text="Button 4"/>

    Sau khi np phn code xml trn ln Activity ta sc giao din nh su

    Giao din trn cho php ta dng ngn tay vut ln mn hnh theo chiu tdi ln.

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    25/94

    Pht trin ng dng SmartphoneAndroid

    24

    2 View

    n vcn bn ca giao din hotrn Android chnh l View. Mt View i din cho mtwidget, trong bi hc ny bn sc hc vskhc nhau gia cc View m bn c thsdng ntrong qu trnh pht trin ng dng android.

    y l mt danh mc cc loi View m chng ta scp trong bi ny:

    - Basic View: y l nhng i tng View thng xuyn sdng nh TextView, EditText,Button.

    - Picker View y l nhng i tng View cho php ngi dng ng dng la chn mtoption, ngy thng, thi gin ny Loi View ny thng hin thdi dng mt danh

    sch cc la chn nh contct, dte time- Display View y l loi i tng View dng hin th hnh nh nh Gllery v

    ImageSwitcher.

    - Menu y l loi i tng View dng to giao din menu la chn

    - Additional View: nhng i tng View nh nlogClock v DigitlClock

    To mt project mi vi cc thng snh su

    Project name: UIExample

    Build target: Android 2.3.3.

    Application name: UI Example

    Package name: android.uiexample

    Create Activity: main

    2.1 Basic Views

    Trong phn ny, ta sxem xt cc View c bn trong android m cho php hin thmt on

    vn bn cng nh thc hin mt scc la chn c bn. Ta stin hnh tm hiu vcc View su y- TextView

    - EditText

    - Button

    - ImageButton

    - CheckBox

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    26/94

    Pht trin ng dng SmartphoneAndroid

    25

    - ToggleButton

    - RadioButton

    - RadioGroup- TextView

    Khi bn to mt project mi trong android, eclipse s to mt file minxml trong th mclyout res/lyout trong n cha mt TextView nh su

    TextViewc sdng hin thmt on vn bn y l mt View c bn thng c sdng trong pht trin ng dng Android. Nu cn cho php ngi sdng chnh s vn bn ng hinthth c thsdng mt subclass ca TextView l EditText y l mt loi View m chng ta sxem xt trong phn sau. Bn cnh TextView, cn c mt sView c bn thng c sdng trongcch ng dng ndroid nh Button, ImgeButton, EditText, CheckBox, ToggleButton, RdioButtonv RadioButton.

    u tin chng ta thm mt file mi trong th mc res/lyout v t cho n mt ci tn l:basic_views.xml v thm vo ni dung nh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    27/94

    Pht trin ng dng SmartphoneAndroid

    26

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    28/94

    Pht trin ng dng SmartphoneAndroid

    27

    android:layout_height="wrap_content"/>

    Ch rng bn sdng thuc tnh id nh ngh cho mi View. Id ca View phi c nh

    dng @+id/tenView

    Trn y chng t sdng cc View su y

    Button: Nt nhn.

    ImageButton:Nt nhn c htrhin thhnh nh trn nt nhn.

    EditText y l mt class con ca TextView, bsung thm khnng cho php chnh s ontext ng hin thtrn n.

    CheckBox: Mt loi nt nhn c bit c hai trng thi: Checked hoc Unchecked.

    RadioGroup and RadioButton:RdioButton cng l loi nt nhn c hai trng thi: Checkedv Unchecked. Mt RdioButton khi check chn th ko thuncheck RdioGroup c sdng nhm mt hoc nhiu i tng RadioButton. Bng cch s gom nhm cc RadioButton vo mtRadioGroup cho php hn chchc check chn mt RadioButton trong cng mt group.

    ToggleButton: Th hin hai trng thi: Check hoc Uncheck c s dng n bo lightindicator).

    xl cc skin thng thng ca cc View ktrn, chng ta to thm mt clss trong thmc src vi tn: BasicViewsExampleActivityjv Su thy i ni dung bng bng phn m sau:

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;importandroid.widget.CheckBox;importandroid.widget.RadioGroup;importandroid.widget.Toast;

    importandroid.widget.ToggleButton;importandroid.widget.RadioGroup.OnCheckedChangeListener;

    publicclassBasicViewsExampleActivityextendsActivity{@OverridepublicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    29/94

    Pht trin ng dng SmartphoneAndroid

    28

    setContentView(R.layout.basic_views);

    //---Button view---Button btnOpen = (Button) findViewById(R.id.btnOpen);btnOpen.setOnClickListener(newView.OnClickListener() {

    publicvoidonClick(View v) {displayToast("You have clicked the Open button");

    }});

    Button btnSave = (Button) findViewById(R.id.btnSave);btnSave.setOnClickListener(newView.OnClickListener(){

    publicvoidonClick(View v) {

    displayToast ("You have clicked the Save button");}

    });

    //---CheckBox---CheckBox checkBox = (CheckBox)

    findViewById(R.id.chkAutosave);checkBox.setOnClickListener(newView.OnClickListener(){

    publicvoidonClick(View v) {if(((CheckBox)v).isChecked())

    displayToast ("CheckBox is checked");elsedisplayToast ("CheckBox is unchecked");

    }});

    //---RadioButton---RadioGroup radioGroup = (RadioGroup)

    findViewById(R.id.rdbGp1);radioGroup.setOnCheckedChangeListener(new

    OnCheckedChangeListener()

    {publicvoidonCheckedChanged(RadioGroup group, intcheckedId) {//---displays the ID of the RadioButton that is checked---

    displayToast(Integer.toString(checkedId));}

    });

    //---ToggleButton---

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    30/94

    Pht trin ng dng SmartphoneAndroid

    29

    ToggleButton toggleButton = (ToggleButton)findViewById(R.id.toggle1);

    toggleButton.setOnClickListener(new

    View.OnClickListener(){

    publicvoidonClick(View v) {if(((ToggleButton)v).isChecked())displayToast ("Toggle button is On");else

    displayToast ("Toggle button is Off");}

    });}

    privatevoiddisplayToast(String msg){

    Toast.makeText(getBaseContext(), msg,Toast.LENGTH_SHORT).show();

    }}Su thy i file ndroidMinifestxml ng k mt Activity mi tn l

    BasicViewsExampleActivity nh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    31/94

    Pht trin ng dng SmartphoneAndroid

    30

    Thm cc dng m sau vo file main.java hin thactivity BasicViewsExampleActivity:

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.content.Intent;importandroid.os.Bundle;

    publicclassmain extendsActivity {/** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Intent intent = new Intent(this,BasicViewsExampleActivity.class);

    startActivity(intent);

    }}

    Thc thi chng trnh v c kt qunh su:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    32/94

    Pht trin ng dng SmartphoneAndroid

    31

    Ta sxem xt li phn code hin thc BasicViewsExamplectivityjv xem cch cc loii tng View hot ng.

    Trc tin BasicViewsExampleActivity l mt class extends class Activity ca Android.BasicViewsExampleActivity sto thnh mt ca sctivity khi n c np ln bi chng trnhTasxem xt phng thcpublic void onCreate(Bundle savedInstanceState)lm r cch hot ngca Button, ImageButton, EditText, CheckBox, ToggleButton, RadioButton v RadioButton.

    Phng thc public void onCreate(Bundle savedInstanceState) nh t bit l phng thcu tin schy khi mt ctivity c np ln mn hnh in thoi Trn phng thc ny ta sgiphng thc setContentView(R.layout.basic_views); thng bo cho Activity hin ti np tt ccci tng ho c khai bo trong file basic_views.xml c t trong th mcres/layout/basic_views.xml). Sau khi np tt c cc i tng ho t file xml ln giao din caActivity ta tin hnh to cc lin kt n cc i tng hom ta cn thy i thuc tnh hoc tcng cc skin ln n. to lin kt n i tng Button c id l btnOpen c khai bo trongfile xml ta sdng on m lnh su y

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    33/94

    Pht trin ng dng SmartphoneAndroid

    32

    Button btnOpen = (Button) findViewById(R.id.btnOpen);btnOpen.setOnClickListener(newView.OnClickListener() {

    publicvoidonClick(View v) {displayToast("You have clicked the Open button");

    }});u tin ta sdng phng thc findViewById(R.id.btnOpen); tm vi tng Button c

    id l btnOpen c khi bo trong file xml Phng thc findViewById(R.id.btnOpen); strvmti tng kiu View nn ta cn p kiu i tng c trvthnh kiu Button v gn cho i tngbtnOpen kiu Button. Ty t c thgi cc phng thc thy i cc thuc tnh c i tngButton nm trn giao din hoca Activity.

    Tip n ta gi phng thc btnOpen.setOnClickListener() gn cho i tng btnOpen

    mt i tng dng lng nghe skin ngi nhn click ln i tng btnOpen. Mt i tngmun x l c skin ngi dng nhn ln Button th i tng phi ci t (implement) liinterface OnClickListener. Interface ny ch c duy nht mt phng thc l public voidonClick(View v). y l phng thc sc gi khi ngi dng nhn ln i tng btnOpen.

    v dny ta skhng xy dng mt class ring bit xl skin ngi dng nhn ln itng btnOpen m ssdng inner class ngay trong BasicViewsExamplectivity nh phn code sau:

    btnOpen.setOnClickListener(newView.OnClickListener() {publicvoidonClick(View v) {

    displayToast("You have clicked the Open button");

    }});y l mt cch khai bo tt mt inner clss v ghi override li phng thc l public void

    onClick(View v) ca interface OnClickListener. Trn phng thc onClick ny t n gin giphngthc displayToast()c ci t trong class BasicViewsExampleActivity. Phng thc ny shin thon text "You have clicked the Open button" bng cch sdng i tng Toast (Ta stmkhng qun tm n i tng Toast trong mc ny ca gio trnh).

    Bng cch ny khi ngi dng nhn ln i tng btnOpen th h thng sgi phng thconClick ktrn. Tham sView v i km c truyn theo phng thc onClick chnh l i tng mngi dng mi tng tc Trong trng hp ny cng chnh l i tng btnOpen). Ta c thsdng

    phng thc vgetId ly vid c i tng c gi km.

    Vi i tng ImgeButton cng tng tnh Button nhng c htrthm thuc tnhandroid:src="@drawable/icon" gn hnh nn cho ImageButton.

    Lu rng tt ccc hnh nh sdng trn giao din ca ng dng android cn phi t trongth mc res/drawable v sdng c php @drwble/tenHinhnh sdng hnh nh trn giaodin ng dng Android (VD: Gn hnh nn cho ImageButton).

    Ta tip tc xem xt i tng CheckBox phn code sau:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    34/94

    Pht trin ng dng SmartphoneAndroid

    33

    CheckBox checkBox = (CheckBox) findViewById(R.id.chkAutosave);checkBox.setOnClickListener(newView.OnClickListener()

    { publicvoidonClick(View v) {if(((CheckBox)v).isChecked())

    displayToast ("CheckBox is checked");else

    displayToast ("CheckBox is unchecked");}

    });Ddng nhn thy dng lnh CheckBox checkBox = (CheckBox)

    findViewById(R.id.chkAutosave); sto lin kt i i tng CheckBox c id l chkAutosave . Sau t cng tip tc gn i tng lng nghe skin ngi dng nhn ln CheckBox nh ca v dv

    Button trn. Trn hm onClick c inner clss c sdng lng nghe skin ngi dng nhnln CheckBox ktrn sp kiu i tng v thnh kiu CheckBox v gi phng thc getChecked()kim tra CheckBox hin ti ng trng thi checked hay unchecked v hin thon text tngng.

    Cch s dng v thuc tnh c ToggleButton cng tng t nh CheckBox, tuy nhinToggleButton c bsung thm n bo light indicator lm ni bt ToggleButton.

    Tip n ta sxem xt cch sdng RdioButton v RdioGroup RdioButton cng tng tnh CheckBox tuy nhin khi gom nhm cc RdioButton v t vo cng mt RadioGroup th ti mtthi im ta chc thchn duy nht mt RadioButton trong cng mt nhm.

    V d: Khi check chn RadioButton c id l rdb1 th rdb2 tchuyn thnh trng thiunchecked. Nu chn li rdb2 th rdb1 tng chuyn thnh trng thi unchecked.

    Ta xem xt phn code xml trch tbasic_views.xml sau:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    35/94

    Pht trin ng dng SmartphoneAndroid

    34

    lm r cch hot ng ca RadioGroup, ta xem xt phn m su y c trch t

    BasicViewsExampleActivity:RadioGroup radioGroup = (RadioGroup) findViewById(R.id.rdbGp1);radioGroup.setOnCheckedChangeListener(newOnCheckedChangeListener(){

    publicvoidonCheckedChanged(RadioGroup group, intcheckedId) {//---displays the ID of the RadioButton that is checked---

    displayToast(Integer.toString(checkedId));}});

    Dng lnh RadioGroup radioGroup = (RadioGroup) findViewById(R.id.rdbGp1); sto linkt n RdioGroup c id l rdbGp1 Su gi phng thcradioGroup.setOnCheckedChangeListener() gn cho rdioGroup i tng sxl skin khi mla chn c cc RdioButton trong RdioGroup rdbGp1 thy i. i tng ny cng l mt khai boinner class tt Trong ci t li phng thc public void onCheckedChanged(RadioGroupgroup, int checkedId) y l phng thc m hthng sgi khi sla chn ca cc RadioButtontrn group thy i Phng thc onCheckedChangedn gin l gi phng thc displayToastin ra id ca RadioButtonhin ti trong group ng trng thi checked.

    i tng ho tip theo chng ta s nghin cu l EditText y l mt sub class ca

    TextView. Ngoi chc nng hin thmt on vn bn nh TextView t cn c thchnh s on texttrn EditText on text m EditText hin thc xc nh bng thuc tnh android:text v c thtruyxut hoc thy i bng cch gi phng thc EditText.getText() v EditText.setText(). Ngoi ra nubn mong mun EditText hin thmt on text di dng cc k tc bit nhm che du ni dungc on text th t thy i thuc tnh ndroidpssword=true nh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    36/94

    Pht trin ng dng SmartphoneAndroid

    35

    2.1.1ProgressBar View

    ProcessBar l kiu i tng View cung cp mt thng tin phn hi trc quan vmt tcvang thc thi di nn.

    VD: Vic download d liu t mt trang web cn phi th hin phn trm d liu download c.

    Sdng ctivity to nh bi trc, thm mt sthnh phn vo basicviews.xml:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    37/94

    Pht trin ng dng SmartphoneAndroid

    36

    Mc nh ProcessBar schIndeterminate - chny n sthhin hiu ng xoaytrn v tn. Chny rt thch hp cho nhng tc vkhng xc nh r c khi no n shon tt.

    V d: Gi dliu n mt webservice no v chi shi p ca server.

    Phn code di y chra cch sdng lung thc thi mt tc vv cp nht li trng thi

    ca ProcessBar sau khi tc vhon tt:packageandroid.uiexample;

    importandroid.app.Activity;importandroid.os.Bundle;importandroid.os.Handler;importandroid.view.View;importandroid.widget.Button;importandroid.widget.CheckBox;importandroid.widget.ProgressBar;importandroid.widget.RadioGroup;importandroid.widget.Toast;importandroid.widget.ToggleButton;importandroid.widget.RadioGroup.OnCheckedChangeListener;

    publicclassBasicViewsExampleActivity extendsActivity{

    Private static intprogress= 0;privateProgressBar progressBar;private int progressStatus= 0;privateHandler handler= newHandler();

    @OverridepublicvoidonCreate(Bundle savedInstanceState){

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

    progressBar= (ProgressBar) findViewById(R.id.progressbar);

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    38/94

    Pht trin ng dng SmartphoneAndroid

    37

    //---do some work in background thread---

    Thread updateProcessBarThread =new

    Thread(new

    Runnable(){publicvoidrun(){//---do some work here---while(progressStatus< 10){

    progressStatus= doSomeWork();}

    //---hides the progress bar---handler.post(newRunnable()

    {publicvoidrun(){

    progressBar.setVisibility(View.GONE);}});

    }

    //---do some long lasting work here---privateintdoSomeWork()

    {try{

    //---simulate doing some work---Thread.sleep(500);

    } catch(InterruptedException e){

    e.printStackTrace();}return++progress;

    }

    });updateProcessBarThread =.start();}

    }

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    39/94

    Pht trin ng dng SmartphoneAndroid

    38

    Phn code pha trn sdng mt lung tnl updateProcessBarThreadtng gi trcabin int processStatus t1 ln 10. Tt ccng vic k trn c thc thi trong hm run() caThread vi ni dung sau:

    publicvoidrun(){

    //---do some work here---while(progressStatus< 10)

    {progressStatus= doSomeWork();

    }

    //---hides the progress bar---handler.post(newRunnable(){

    publicvoidrun(){

    progressBar.setVisibility(View.GONE);}

    });

    }

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    40/94

    Pht trin ng dng SmartphoneAndroid

    39

    Trong Thread sthc hin mt vng lp while thc thi lin tc khi processStatus=10 chng trnh sgi phng thc hndlerpost post mt i tng implementinterface Runable(). Interface Runable chc duy nht mt phng thc run. Dohandle l i tngc khi to phn khai bo cc thuc tnh ca BasicViewsExampleActivity nn l mt i tngHandle gn vi thed m ctivity BsicViewsExmplectivity ng thc thi. Do vy khi ta post mti tng Runble th i tng ny s c vo messge queue v thc thi trn thread caBasicViewsExampleActivity. iu ny nghe chng nh lm rc ri thm phn code ca chng ta tuynhin n l cn thit bi v lnh progressBar.setVisibility(View.GONE); khng ththc thi trn threadupdateProcessBarThread. Tt ccc cu lnh lin qun n thy i thuc tnh c cc i tng hochc ththc thi trn UIThread. Chnh v vy ta phi gi mt i tng Runble n thread caBasicViewsExampleActivity thc thi vic thy i ProcessBar.

    Nu bn khng mun sdng ProcessBar vi chIndeterminate, bn c thchuyn chProcessBar vchhin thdi dng mt thanh ngang thhin phn trm ca tc v.

    Phn code di dy sdng mt lung tng phn trm cng vic t1 n 100:

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.os.Bundle;importandroid.os.Handler;importandroid.view.View;importandroid.widget.Button;importandroid.widget.CheckBox;

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    41/94

    Pht trin ng dng SmartphoneAndroid

    40

    importandroid.widget.ProgressBar;importandroid.widget.RadioGroup;import

    android.widget.Toast;importandroid.widget.ToggleButton;importandroid.widget.RadioGroup.OnCheckedChangeListener;

    publicclassBasicViewsExampleActivity extendsActivity{

    Private static intprogress= 0;privateProgressBar progressBar;private int progressStatus= 0;privateHandler handler= newHandler();

    @OverridepublicvoidonCreate(Bundle savedInstanceState)

    {super.onCreate(savedInstanceState);setContentView(R.layout.basic_views);progressBar= (ProgressBar) findViewById(R.id.progressbar);

    //---do some work in background thread---Thread updateProcessBarThread = newThread(new Runnable()

    {publicvoidrun()

    {while(progressStatus< 100)

    {progressStatus= doSomeWork();

    //---Update the progress bar---handler.post(new Runnable()

    {publicvoidrun() {progressBar.setProgress(progressStatus);

    }

    });

    }//---hides the progress bar---handler.post(new Runnable()

    {publicvoidrun() {//---0 - VISIBLE; 4 - INVISIBLE; 8 - GONE---progressBar.setVisibility(8);

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    42/94

    Pht trin ng dng SmartphoneAndroid

    41

    }});

    }

    //---do some long lasting work here---privateintdoSomeWork()

    {try{//---simulate doing some work---

    Thread.sleep(500);} catch(InterruptedException e){

    e.printStackTrace();}

    return++progress;}

    });updateProcessBarThread.start();}

    }

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    43/94

    Pht trin ng dng SmartphoneAndroid

    42

    Mi ln tng mt n v phn trm cng vic ta li update ProcessBar bng phng thcprogressBar.setProgress(progressStatus);. Phn trm cng vic s th hin tng ng trn thanh

    ProcessBr nh trn hnh

    2.1.2AutoComplete TextView

    AutoCompletel mt loi View tng t vi EditText (Trn thc t AutoComplete l mtsubclass ca EditText). Ngoi nhng chc nng tng tnh EditText n cn c khnng r mtdanh sch cc gi tng tnh phn text m ngi dng nhp vo. Thm mt file autocomplete.xmlvo th mc res/layout vi ni dung nh su

    Thm mt file AutoCompleteExampleActivity.java vi ni dung nh su

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.ArrayAdapter;importandroid.widget.AutoCompleteTextView;

    publicclassAutoCompleteExampleActivity extendsActivity{

    String[] presidents={

    "Dwight D. Eisenhower",

    "John F. Kennedy","Lyndon B. Johnson","Richard Nixon","Gerald Ford","Jimmy Carter","Ronald Reagan","George H. W. Bush","Bill Clinton","George W. Bush",

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    44/94

    Pht trin ng dng SmartphoneAndroid

    43

    "Barack Obama"};

    @OverridepublicvoidonCreate(Bundle savedInstanceState)

    {super.onCreate(savedInstanceState);

    setContentView(R.layout.autocomplete);

    ArrayAdapter adapter = newArrayAdapter(this,

    android.R.layout.simple_dropdown_item_1line,presidents);

    AutoCompleteTextView textView = (AutoCompleteTextView)findViewById(R.id.txtCountries);

    textView.setThreshold(3);textView.setAdapter(adapter);

    }

    }

    Ch rng dnh sch c r c cha trong mt i tng rrydpter Phng thcsetThreshold t s nh nht ca cc k t m user phi nhp trc khi r cc text trongArrayAdapter.

    Thm nhng dng sau vo file Manifest.xml:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    45/94

    Pht trin ng dng SmartphoneAndroid

    44

    Bsung vo file activity chnh khi khi chy ng dng nh su

    packageandroid.uiexample;

    importandroid.app.Activity;

    importandroid.content.Intent;importandroid.os.Bundle;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;

    publicclassmain extendsActivity {/** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Intent intent = new Intent(this,AutoCompleteExampleActivity.class);

    startActivity(intent);}

    }

    Thc thi chng trnh v nhp thmt on text snhn c kt qunh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    46/94

    Pht trin ng dng SmartphoneAndroid

    45

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    47/94

    Pht trin ng dng SmartphoneAndroid

    46

    2.2 PickerView

    2.2.1TimePicker

    TimePicker l View cho php ngi sdng chn thi gian ca mt ngy, trong chai ch24h hoc chAM, PM.

    Thm mt class DateTimePickerExampleActivity.java vi ni dung nh su

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.os.Bundle;

    importandroid.widget.TimePicker;

    publicclassDateTimePickerExampleActivity extendsActivity{

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);

    setContentView(R.layout.datetimepicker);}

    }Bsung trong file AndroidManifest.xml ng k mt Activity mi :

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    48/94

    Pht trin ng dng SmartphoneAndroid

    47

    B sung vo file mainjv khi chy activity DateTimePickerExamplectivity nh su:

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.content.Intent;importandroid.os.Bundle;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;

    publicclassmain extendsActivity {/** Called when the activity is first created. */@Override

    publicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Intent intent = new Intent(this,DateTimePickerExampleActivity.class);

    startActivity(intent);}

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    49/94

    Pht trin ng dng SmartphoneAndroid

    48

    }

    Thc thi chng trnh t snhn c kt qunh su

    ly thi gian trn TimPicker ta cn to lin kt n n v gi getCurrentHour() vgetCurrentMinute() ly giv pht trn TimePicker.

    Ngoi ra ta c th hin th TimePicker trn mt Dialog Window. B sung vo

    DateTimePickerExampleActivityjv on m nh su

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.app.Dialog;importandroid.app.TimePickerDialog;importandroid.os.Bundle;importandroid.widget.TimePicker;

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    50/94

    Pht trin ng dng SmartphoneAndroid

    49

    importandroid.widget.Toast;

    publicclassDateTimePickerExampleActivity

    extendsActivity{

    int hour, minute;static final int TIME_DIALOG_ID= 0;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.datetimepicker);showDialog(TIME_DIALOG_ID);}

    @OverrideprotectedDialog onCreateDialog(intid){switch(id) {caseTIME_DIALOG_ID:return newTimePickerDialog(this, mTimeSetListener, hour,

    minute,false);}Return null;}

    privateTimePickerDialog.OnTimeSetListenermTimeSetListener=newTimePickerDialog.OnTimeSetListener()

    {publicvoidonTimeSet(TimePicker view, inthourOfDay, int

    minuteOfHour){hour= hourOfDay;minute= minuteOfHour;Toast.makeText(getBaseContext(),

    "You have selected : "+ hour+ ":"+ minute,

    Toast.LENGTH_SHORT).show();}};

    }

    Khi thc thi chng trnh t sc kt qunh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    51/94

    Pht trin ng dng SmartphoneAndroid

    50

    2.2.2DatePicker

    Ging nh TimePicker View, DatePicker cho php ngi dng chn date Thy i filedatetimepicker.xml thnh ni dung nh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    52/94

    Pht trin ng dng SmartphoneAndroid

    51

    Thy i ni dung c file DteTimePickerExmplectivity nh su

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);setContentView(R.layout.datetimepicker);//showDialog(TIME_DIALOG_ID);

    }

    Khi thc thi chng trnh t sc kt qunh su

    Hin ThDatePicker View trong mt Dialog Window

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    53/94

    Pht trin ng dng SmartphoneAndroid

    52

    Bn cng c th hin th DatePicker View trong mt Dilog su b sung vo fileDatePickerExampleActivityjv on m nhsau:

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.app.DatePickerDialog;importandroid.app.Dialog;importandroid.app.TimePickerDialog;importandroid.os.Bundle;importandroid.widget.DatePicker;importandroid.widget.TimePicker;importandroid.widget.Toast;

    publicclassDateTimePickerExampleActivity extendsActivity{

    int hour, minute;int Year=2010, month=1, day=1;

    static final int TIME_DIALOG_ID= 0;static final int DATE_DIALOG_ID= 1;

    @OverrideProtected voidonCreate(Bundle savedInstanceState)

    {

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

    showDialog(DATE_DIALOG_ID);}

    @OverrideprotectedDialog onCreateDialog(intid)

    {switch(id) {case TIME_DIALOG_ID:return newTimePickerDialog(

    this, mTimeSetListener, hour, minute, false);

    case DATE_DIALOG_ID:return newDatePickerDialog(this, mDateSetListener, Year, month, day);

    }Return null;

    }

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    54/94

    Pht trin ng dng SmartphoneAndroid

    53

    privateTimePickerDialog.OnTimeSetListener mTimeSetListener=newTimePickerDialog.OnTimeSetListener()

    {

    @OverridepublicvoidonTimeSet(TimePicker view, inthourOfDay,

    intminute) {// TODOAuto-generated method stub

    }//...

    };

    privateDatePickerDialog.OnDateSetListener mDateSetListener=newDatePickerDialog.OnDateSetListener()

    {publicvoidonDateSet(DatePicker view, intyear, intmonthOfYear,intdayOfMonth)

    {Year= year;month= monthOfYear;day= dayOfMonth;

    Toast.makeText(getBaseContext(),"You have selected : "+ (month+ 1) +

    "/"+ day+ "/"+ Year,Toast.LENGTH_SHORT).show();

    }};

    }

    Thc thi chng trnh t sc kt qunh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    55/94

    Pht trin ng dng SmartphoneAndroid

    54

    2.2.3List Views

    ListView hin thmt danh sch cc phn tkhc nhau trn mt giao din cho php cun theo

    chiu dc tm hiu cch hot ng ca ListView hy to thm mt file listviewxml trong th mcres/lyout nh su

    Su thm mt class mi trong src, v t tn cho n l ListViewExampleActivity.javavini dung nh su

    packageandroid.uiexample;

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    56/94

    Pht trin ng dng SmartphoneAndroid

    55

    importandroid.app.Activity;import

    android.app.ListActivity;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.ArrayAdapter;importandroid.widget.ListView;importandroid.widget.Toast;

    publicclassListViewExampleActivity extendsListActivity{

    String[] presidents= {"Dwight D. Eisenhower","John F. Kennedy","Lyndon B. Johnson","Richard Nixon","Gerald Ford","Jimmy Carter","Ronald Reagan","George H. W. Bush","Bill Clinton","George W. Bush","Barack Obama"

    };

    @OverridepublicvoidonCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);setContentView(R.layout.listview);setListAdapter(newArrayAdapter(this,

    android.R.layout.simple_list_item_1, presidents));}

    publicvoidonListItemClick(ListView parent, View v,intposition, longid)

    {Toast.makeText(this, "You have selected "+

    presidents[position], Toast.LENGTH_SHORT).show();}

    }

    Ch rng ListViewExampleActivity ktha tListActivity, v khng qun bsung vo filendroidMnifestxml ng k mt Activity mi:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    57/94

    Pht trin ng dng SmartphoneAndroid

    56

    Cui cng chng ta chnh sa file mainjv khi chy ListViewExampleActivity:

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.content.Intent;importandroid.os.Bundle;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;

    publicclassmain extendsActivity {/** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    58/94

    Pht trin ng dng SmartphoneAndroid

    57

    Intent intent = new Intent(this,ListViewExampleActivity.class);

    startActivity(intent);}

    }

    Thc thi chng trnh t sc kt qunh su

    2.2.4Spinner View

    Spinner View l loi View c dng hin th mt danh mc cho php ngi dng lachn lm rcch hot ng ca Spinner t thm file spinnerxml trong th mc res/layout vi nidung nh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    59/94

    Pht trin ng dng SmartphoneAndroid

    58

    Thm mt class mi trong src v t tn l SpinnerExampleActivity.java vi ni dung nh su packageandroid.uiexample;

    importandroid.app.Activity;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.AdapterView;importandroid.widget.AdapterView.OnItemSelectedListener;importandroid.widget.ArrayAdapter;importandroid.widget.Spinner;importandroid.widget.Toast;

    publicclassSpinnerExampleActivity extendsActivity {

    String[] presidents= {"Dwight D. Eisenhower","John F. Kennedy","Lyndon B. Johnson","Richard Nixon","Gerald Ford","Jimmy Carter","Ronald Reagan",

    "George H. W. Bush","Bill Clinton","George W. Bush","Barack Obama"

    };

    Spinner s1;

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    60/94

    Pht trin ng dng SmartphoneAndroid

    59

    @OverridepublicvoidonCreate(Bundle savedInstanceState)

    {super.onCreate(savedInstanceState);setContentView(R.layout.spinner);

    s1= (Spinner) findViewById(R.id.spinner1);

    ArrayAdapter adapter = newArrayAdapter(this,android.R.layout.simple_spinner_item, presidents);

    s1.setAdapter(adapter);s1.setOnItemSelectedListener(newOnItemSelectedListener(){

    @OverridepublicvoidonItemSelected(AdapterView arg0, View arg1,

    intarg2, longarg3){intindex = s1.getSelectedItemPosition();Toast.makeText(getBaseContext(),"You have selected item :

    "+ presidents[index], Toast.LENGTH_SHORT).show();}

    publicvoidonNothingSelected(AdapterView arg0){

    }});}

    }

    B sung file ndroidMnifestxml ng k ctivity mi:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    61/94

    Pht trin ng dng SmartphoneAndroid

    60

    Chnh sa file mainjv nh su

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.content.Intent;importandroid.os.Bundle;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;

    publicclassmain extendsActivity {/** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Intent intent = new Intent(this,

    SpinnerExampleActivity.class);startActivity(intent);

    }

    }

    Thc thi chng trnh v c kt qunh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    62/94

    Pht trin ng dng SmartphoneAndroid

    61

    Thay v hin thcc mc di dng mt danh sch n nh hnh trn th bn cn c thhin thchng bng cch sdng RadioButton. lm vic ny chcn chnh sa li tham sth2 trong hm dng ArrayAdapter:

    ArrayAdapter adapter = newArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item, presidents);

    Thc thi chng trnh v nhn kt qunh su:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    63/94

    Pht trin ng dng SmartphoneAndroid

    62

    2.3 Display Views

    2.3.1Gallery and ImageView

    Gallery l mt loi View hin th cc mc di dng mt danh sch cun ngang v cnhphn ttrung tm Hnh di y l mt Gllery c sdng trn Android Market:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    64/94

    Pht trin ng dng SmartphoneAndroid

    63

    tm hiu cch hot ng ca Gallery, ta to thm mt file displyviewxml trong th mcres/layout vi ni dung nh su

    Thm mt file mi trong res/vlues t tn l attrs.xml vi ni dung nh su

    Gllery1 c sdng p dng hin thcc images trong Gallery v mi image sc mtborder bao quanh n, hnh minh ha :

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    65/94

    Pht trin ng dng SmartphoneAndroid

    64

    Thm mt simage trong th mc res/drwble nh sau:

    Thm mt classDisplayViewsExampleActivity.javatrong src/android/uiexample vi ni dung

    nh su:packageandroid.uiexample;

    importandroid.app.Activity;importandroid.content.Context;importandroid.content.res.TypedArray;importandroid.os.Bundle;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.AdapterView;importandroid.widget.AdapterView.OnItemClickListener;

    importandroid.widget.BaseAdapter;importandroid.widget.Gallery;importandroid.widget.ImageView;importandroid.widget.Toast;

    publicclassDisplayViewsExampleActivityextendsActivity{//---the images to display---Integer[] imageIDs= {

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    66/94

    Pht trin ng dng SmartphoneAndroid

    65

    R.drawable.pic1,R.drawable.pic2,

    R.drawable.pic3,R.drawable.pic4,R.drawable.pic5,R.drawable.pic6,R.drawable.pic7

    };

    @OverridepublicvoidonCreate(Bundle savedInstanceState)

    {super.onCreate(savedInstanceState);

    setContentView(R.layout.displayview);

    Gallery gallery = (Gallery)findViewById(R.id.gallery1);

    gallery.setAdapter(newImageAdapter(this));gallery.setOnItemClickListener(new

    OnItemClickListener(){

    publicvoidonItemClick(AdapterView parent,View v, intposition, longid){

    Toast.makeText(getBaseContext(),"pic"+ (position + 1) + " selected",

    Toast.LENGTH_SHORT).show();}

    });}

    publicclassImageAdapter extendsBaseAdapter{

    privateContext context;privateintitemBackground;

    publicImageAdapter(Context c){

    context= c;//---setting the style---

    TypedArray a =obtainStyledAttributes(R.styleable.Gallery1);itemBackground= a.getResourceId(

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    67/94

    Pht trin ng dng SmartphoneAndroid

    66

    R.styleable.Gallery1_android_galleryItemBackground, 0);

    a.recycle();}

    //---returns the number of images---publicintgetCount() {returnimageIDs.length;

    }

    //---returns the ID of an item---publicObject getItem(intposition) {returnposition;

    }

    publiclonggetItemId(intposition) {returnposition;

    }

    //---returns an ImageView view---publicView getView(intposition, View convertView, ViewGroupparent) {

    ImageView imageView = newImageView(context);imageView.setImageResource(imageIDs[position]);imageView.setScaleType(ImageView.ScaleType.FIT_XY);

    imageView.setLayoutParams(newGallery.LayoutParams(150, 120));

    imageView.setBackgroundResource(itemBackground);returnimageView;

    }}

    }

    Trong v dtrn ta to mt class ImageAdapter (Class ny kth Bsedpter dng ktni mt lot cc i tng ImgeView n i tng Gallery. Nhng i tng ImageView ny s

    c dng hin thhnh nh trong Gallery. ImageAdapter sto cung cp hi hm cn bn sau:- public int getCount(): Trvslng ImageView c trong Gallery.

    - public View getView(int position, View convertView, ViewGroup parent): Trvi tng ImageView shin thti mt vtr xc nh.

    Trong v dtrn c sdng phng thc setOnItemClickListener gn i tng lng ngheskin ngi dng nhn ln mi ImgeView trong Gllery y cng l mt khai bo inner class. Khi

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    68/94

    Pht trin ng dng SmartphoneAndroid

    67

    ngi dng nhn ln mt ImageView trong Gallery th h thng s t gi phng thcpublic voidonItemClick(AdapterView parent, View v, int position, long id)

    Bsung trong file AndroidManifest.xml vi ni dung nh sau:

    v b sung trong file mainjv nh su

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.content.Intent;importandroid.os.Bundle;importandroid.view.View;importandroid.view.View.OnClickListener;

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    69/94

    Pht trin ng dng SmartphoneAndroid

    68

    importandroid.widget.Button;

    publicclassmain

    extendsActivity {/** Called when the activity is first created. */

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Intent intent = new Intent(this,DisplayViewsExampleActivity.class);

    startActivity(intent);}

    }

    Thc thi chng trnh v nhn kt qunh su:

    Thy i phng thc onItemClick hin thhnh nh khi nhn vo mt item vi ni dungnh su:

    publicvoidonItemClick(AdapterView parent, View v, intposition, longid){

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    70/94

    Pht trin ng dng SmartphoneAndroid

    69

    ImageView imageView = (ImageView)findViewById(R.id.image1);

    imageView.setImageResource(imageIDs[position]);

    }

    2.3.2ImageSwitcher

    Phn trc chng t hc cch sdng mt Gllery hin thmt lot ImgeView didng hnh nh thu nh Khi ngi dng nhn ln mt ImageView th n shin thln ImageView bndi. Do kiu hin thny rt phbin nn ndroid htrsn mt loi View tn l ImageSwitchercho cch hin thhnh nh nh trn

    Tin hnh thy i ni dung ca file displayview.xml nhsau:

    Thy i ni dung ca file DisplayViewsExampleActivityjv nh su

    packageandroid.uiexample;

    importandroid.app.Activity;

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    71/94

    Pht trin ng dng SmartphoneAndroid

    70

    importandroid.content.Context;importandroid.content.res.TypedArray;import

    android.os.Bundle;importandroid.view.View;importandroid.view.ViewGroup;importandroid.view.ViewGroup.LayoutParams;importandroid.view.animation.AnimationUtils;importandroid.widget.AdapterView;importandroid.widget.AdapterView.OnItemClickListener;importandroid.widget.BaseAdapter;importandroid.widget.Gallery;importandroid.widget.ImageSwitcher;importandroid.widget.ImageView;importandroid.widget.Toast;importandroid.widget.ViewSwitcher.ViewFactory;

    publicclassDisplayViewsExampleActivity extendsActivityimplementsViewFactory{

    //---the images to display---Integer[] imageIDs= {

    R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4,R.drawable.pic5,

    R.drawable.pic6,R.drawable.pic7

    };

    privateImageSwitcher imageSwitcher;

    @OverridepublicvoidonCreate(Bundle savedInstanceState)

    {super.onCreate(savedInstanceState);

    setContentView(R.layout.displayview);

    imageSwitcher= (ImageSwitcher) findViewById(R.id.switcher1);imageSwitcher.setFactory(this);imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,

    android.R.anim.fade_in));imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,

    android.R.anim.fade_out));

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    72/94

    Pht trin ng dng SmartphoneAndroid

    71

    Gallery gallery = (Gallery)findViewById(R.id.gallery1);

    gallery.setAdapter(new

    ImageAdapter(this

    ));gallery.setOnItemClickListener(newOnItemClickListener()

    {publicvoidonItemClick(AdapterView parent,

    View v, intposition, longid){

    imageSwitcher.setImageResource(imageIDs[position]);}

    });}

    publicView makeView(){

    ImageView imageView = newImageView(this);imageView.setBackgroundColor(0xFF000000);imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);imageView.setLayoutParams(new

    ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));

    returnimageView;}

    publicclassImageAdapter extendsBaseAdapter{

    privateContext context;privateintitemBackground;

    publicImageAdapter(Context c){

    context= c;

    //---setting the style---

    TypedArray a =obtainStyledAttributes(R.styleable.Gallery1);itemBackground= a.getResourceId(

    R.styleable.Gallery1_android_galleryItemBackground, 0);a.recycle();

    }

    //---returns the number of images---

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    73/94

    Pht trin ng dng SmartphoneAndroid

    72

    publicintgetCount(){

    returnimageIDs.length;}

    //---returns the ID of an item---publicObject getItem(intposition)

    {returnposition;

    }

    publiclonggetItemId(intposition){

    returnposition;

    }

    //---returns an ImageView view---publicView getView(intposition, View convertView, ViewGroupparent)

    {ImageView imageView = newImageView(context);imageView.setImageResource(imageIDs[position]);imageView.setScaleType(ImageView.ScaleType.FIT_XY);imageView.setLayoutParams(new

    Gallery.LayoutParams(150, 120));

    imageView.setBackgroundResource(itemBackground);returnimageView;

    }}

    }

    Khi thc thi chng trnh t sc kt qunh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    74/94

    Pht trin ng dng SmartphoneAndroid

    73

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    75/94

    Pht trin ng dng SmartphoneAndroid

    74

    2.3.3GridView

    The GridView view shows items in two-dimensional scrolling grid. You can use the GridView

    view together with ImageView views to display a series of images.Thy i file displayview.xml vi ni dung nh su

    Thy i ni dung file DispalyViewsExamplectivityjv nhsau:

    importandroid.app.Activity;importandroid.content.Context;

    importandroid.os.Bundle;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.AdapterView;importandroid.widget.AdapterView.OnItemClickListener;importandroid.widget.BaseAdapter;importandroid.widget.GridView;importandroid.widget.ImageView;importandroid.widget.Toast;

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    76/94

    Pht trin ng dng SmartphoneAndroid

    75

    publicclassDisplayViewsExampleActivity extendsActivity{

    //---the images to display---Integer[] imageIDs= {R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4,R.drawable.pic5,R.drawable.pic6,R.drawable.pic7,R.drawable.pic8

    };

    @OverridepublicvoidonCreate(Bundle savedInstanceState)

    {super.onCreate(savedInstanceState);

    setContentView(R.layout.displayview);

    GridView gridView = (GridView)findViewById(R.id.gridview);

    gridView.setAdapter(newImageAdapter(this));

    gridView.setOnItemClickListener(new

    OnItemClickListener(){

    publicvoidonItemClick(AdapterView parent,View v, intposition, longid){

    Toast.makeText(getBaseContext(),"pic"+ (position + 1) + " selected",

    Toast.LENGTH_SHORT).show();}

    });}

    publicclassImageAdapter extendsBaseAdapter{

    privateContext context;

    publicImageAdapter(Context c){

    context= c;}

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    77/94

    Pht trin ng dng SmartphoneAndroid

    76

    //---returns the number of images---publicint

    getCount() {returnimageIDs.length;}

    //---returns the ID of an item---publicObject getItem(intposition) {returnposition;

    }

    publiclonggetItemId(intposition) {returnposition;

    }

    //---returns an ImageView view---publicView getView(intposition, View convertView, ViewGroupparent)

    {ImageView imageView;if(convertView == null) {

    imageView = newImageView(context);imageView.setLayoutParams(new

    GridView.LayoutParams(85, 85));

    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);imageView.setPadding(5, 5, 5, 5);

    } else{imageView = (ImageView) convertView;

    }imageView.setImageResource(imageIDs[position]);

    returnimageView;}

    }

    }

    Thc thi chng trnh t sc kt qunh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    78/94

    Pht trin ng dng SmartphoneAndroid

    77

    2.4 Menus

    Menus l mt la chn rt hu dng hin ththm cc ty chn m n khng trc tip hinthtrn giao din chnh ca ng dng. C hai loi menu trn Android:

    Context Menu: Hin th nhng thng tin lin qun n mt i tng View c th. Trnndroid, kch hot ContextMenu ngi dng cn nhn-v-gi mt i tng View(Button,ImgeView

    Options Menu: Hin thnhng thng tin lin qun n Activity hin ti Trong ndroid, kch hot Options Menu ngi dng cn nhn nt Menu trn thit b.

    Hnh sau l mt v dca mt Options Menu trn ng dng browser. Dng menu ny shinthkhi ngi dng nhn phm Menu trn thit b:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    79/94

    Pht trin ng dng SmartphoneAndroid

    78

    Hnh tip theo l mt Context Menu. kch hot Context Menu, ngi sdng nhn-v-gimt i tng View trn mn hnh hoc chn mt i tng View v nhn phm trung tm (center-button) trn thit b.

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    80/94

    Pht trin ng dng SmartphoneAndroid

    79

    thy rcch thc sdng menu trn Android, ta tin hnh thm mt file menu.xml trongth mc res/layout vi ni dung nh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    81/94

    Pht trin ng dng SmartphoneAndroid

    80

    Bsung file AndroidManifest.xml vi ni dung nh su

    Tin hnh to mi mt file MenuExampleActivity.java v to 02 phng thc h trcreateMenu v menuChoice vi ni dung nh su:

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.os.Bundle;importandroid.view.Menu;

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    82/94

    Pht trin ng dng SmartphoneAndroid

    81

    importandroid.view.MenuItem;importandroid.view.View.OnCreateContextMenuListener;import

    android.widget.Button;importandroid.widget.Toast;

    publicclassMenuExampleActivity extendsActivity implementsOnCreateContextMenuListener{

    @OverridepublicvoidonCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);

    setContentView(R.layout.menu);}

    privatevoidcreateMenu(Menu menu){

    menu.setQwertyMode(true);MenuItem mnu1 = menu.add(0, 0, 0, "Item 1");{

    mnu1.setAlphabeticShortcut('a');mnu1.setIcon(R.drawable.icon);

    }MenuItem mnu2 = menu.add(0, 1, 1, "Item 2");

    {mnu2.setAlphabeticShortcut('b');mnu2.setIcon(R.drawable.icon);

    }MenuItem mnu3 = menu.add(0, 2, 2, "Item 3");{

    mnu3.setAlphabeticShortcut('c');mnu3.setIcon(R.drawable.icon);

    }MenuItem mnu4 = menu.add(0, 3, 3, "Item 4");{

    mnu4.setAlphabeticShortcut('d');}menu.add(0, 3, 3, "Item 5");menu.add(0, 3, 3, "Item 6");menu.add(0, 3, 3, "Item 7");

    }

    privatebooleanmenuChoice(MenuItem item){

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    83/94

    Pht trin ng dng SmartphoneAndroid

    82

    switch(item.getItemId()) {case0:

    Toast.makeText(this

    , "You clicked on Item 1",Toast.LENGTH_LONG).show();returntrue;case1:

    Toast.makeText(this, "You clicked on Item 2",Toast.LENGTH_LONG).show();

    returntrue;case2:

    Toast.makeText(this, "You clicked on Item 3",Toast.LENGTH_LONG).show();

    returntrue;case3:

    Toast.makeText(this, "You clicked on Item 4",Toast.LENGTH_LONG).show();

    returntrue;case4:

    Toast.makeText(this, "You clicked on Item 5",Toast.LENGTH_LONG).show();

    returntrue;case5:

    Toast.makeText(this, "You clicked on Item 6",Toast.LENGTH_LONG).show();

    returntrue;

    case6:Toast.makeText(this, "You clicked on Item 7",

    Toast.LENGTH_LONG).show();returntrue;

    }returnfalse;

    }

    }

    Phng thc createMenu() cc tc dng to mt danh sch cc menu item Phng thc

    publicMenuItemadd(int groupId, int itemId, int order, CharSequence title)s thm mt menuitem v menu hin ti vi cc thng sxc nh cc thuc tnh ca menu item c thm vo Phngthc public MenuItemsetAlphabeticShortcut(char alphaChar)s gn phm tt bn phm mnhanh mt menu item. Phng thc publicMenuItemsetIcon(int iconRes)sgn mt hnh nh dnglm biu tng cho menu item mi thm vo.

    Tip theo thm hai file hnhreminder.png v warning.pngtrong th mc res/drawable nhsau:

    http://d/Program%20Files/eclipse/android-sdk-windows/docs/reference/android/view/MenuItem.htmlhttp://d/Program%20Files/eclipse/android-sdk-windows/docs/reference/android/view/MenuItem.htmlhttp://d/Program%20Files/eclipse/android-sdk-windows/docs/reference/android/view/MenuItem.htmlhttp://d/Program%20Files/eclipse/android-sdk-windows/docs/reference/android/view/MenuItem.html
  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    84/94

    Pht trin ng dng SmartphoneAndroid

    83

    2.4.1.1 Option menu

    hin thOption menu trn Activity, ta cn orverride hi phng thconCreteOptionsMenu v onOptionsItemSelected Phng thc onCreateOptionsMenu() c gikhi ngi dng nhn ln phm Menu trn thit b. Ti phng thc ny ta s gi phng thccreteMenu t khi bo trn khi to menu cho Option menu Phng thconOptionsItemSelected() sc gi khi ngi dng nhn chn mt menu item trn Option menu. Tiphng thc ny ta stin hnh gi phng thc menuChoice t nh ngh trn xl s

    kin ngi dng nhn chn menu item.

    Thy i file MenuExampleActivity.java vi ni dung nh su

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.os.Bundle;importandroid.view.Menu;importandroid.view.MenuItem;importandroid.view.View.OnCreateContextMenuListener;importandroid.widget.Button;importandroid.widget.Toast;

    publicclassMenuExampleActivity extendsActivity implementsOnCreateContextMenuListener{

    @OverridepublicvoidonCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);

    setContentView(R.layout.menu);

    }

    privatevoidcreateMenu(Menu menu){

    // Xem mc trn}

    privatebooleanmenuChoice(MenuItem item)

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    85/94

    Pht trin ng dng SmartphoneAndroid

    84

    {// Xem mc trn

    }

    @OverridepublicbooleanonCreateOptionsMenu(Menu menu) {super.onCreateOptionsMenu(menu);

    createMenu(menu);returntrue;

    }

    @OverridepublicbooleanonOptionsItemSelected(MenuItem item)

    {returnmenuChoice(item);

    }

    }

    Thc thi chng trnh, nhn nt Menu trn thit bnhn c kt qunh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    86/94

    Pht trin ng dng SmartphoneAndroid

    85

    2.4.1.2 Context menu

    Nu mun gn mt Menu ln mt i tng View ta cn gi phng thcsetOnCreateContextMenuListener()gn i tng nhn nhim v to ContextMenu Thy i fileMenuExampleActivity vi ni dung nh su

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.os.Bundle;importandroid.view.ContextMenu;importandroid.view.ContextMenu.ContextMenuInfo;importandroid.view.Menu;importandroid.view.MenuItem;importandroid.view.View;importandroid.view.View.OnCreateContextMenuListener;

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    87/94

    Pht trin ng dng SmartphoneAndroid

    86

    importandroid.widget.Button;importandroid.widget.Toast;

    publicclassMenuExampleActivity extendsActivity implementsOnCreateContextMenuListener{

    @OverridepublicvoidonCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);

    setContentView(R.layout.menu);

    Button btn = (Button) findViewById(R.id.btn1);btn.setOnCreateContextMenuListener(this);

    }

    privatevoidcreateMenu(Menu menu){// Xem phn trn

    }

    privatebooleanmenuChoice(MenuItem item){

    // Xem phn trn}

    @OverridepublicvoidonCreateContextMenu(ContextMenu menu, View view,ContextMenuInfo menuInfo)

    {super.onCreateContextMenu(menu, view, menuInfo);createMenu(menu);

    }

    @OverridepublicbooleanonContextItemSelected(MenuItem item)

    {returnmenuChoice(item);

    }

    }

    Thc thi chng trnh nhn c kt qunh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    88/94

    Pht trin ng dng SmartphoneAndroid

    87

    2.5 Additional View

    2.5.1AnalogClock v DigitalClock

    Thy i file main.xml vi ni dung nh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    89/94

    Pht trin ng dng SmartphoneAndroid

    88

    android:layout_height="wrap_content"/>

    Thy i ni dung file main.java vi ni dung nh su

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.os.Bundle;

    publicclassmain extendsActivity {/** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

    setContentView(R.layout.main);}

    }

    Thc thi chng trnh nhn c kt qunh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    90/94

    Pht trin ng dng SmartphoneAndroid

    89

    2.5.2WebView

    WebView l mt loi View cho php hin th mt ni dung HTML trn giao din ca ngdng tm hiu vcch hot ng ca WebView ta tin hnh thm mt file webviewxml vo thmc res/layout vi ni dung nh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    91/94

    Pht trin ng dng SmartphoneAndroid

    90

    android:layout_height="wrap_content"android:text="Hello, world!"

    />

    Thm mt file WebViewExampleActivityjv trong th mc src/android/uiexample vi ni

    dung nh su

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.os.Bundle;importandroid.webkit.WebView;

    publicclassWebViewExampleActivity extendsActivity{/** Called when the activity is first created. */

    @OverridepublicvoidonCreate(Bundle savedInstanceState)

    {super.onCreate(savedInstanceState);

    setContentView(R.layout.webview);

    WebView wv = (WebView) findViewById(R.id.webview1);wv.loadUrl("http://www.hoasen.edu.vn");

    }

    }

    ng k mi mt Activity trong file AndroidManifest.xml v gn quyn truy cp Internet chong dng:

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    92/94

    Pht trin ng dng SmartphoneAndroid

    91

    Thy i ni dung ca file main.java bt Activity WebViewExampleActivity:

    packageandroid.uiexample;

    importandroid.app.Activity;importandroid.content.Intent;importandroid.os.Bundle;

    publicclassmain extendsActivity {/** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Intent intent = new Intent(this,WebViewExampleActivity.class);

    startActivity(intent);}

    }

    Thc thi chng trnh nhn c kt qunh su

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    93/94

    Pht trin ng dng SmartphoneAndroid

    92

    Ngoi cch hin thni dung HTML ly tinternet vt cng c thhin thni dung HTMLbng cch to ra chui c ni dung nh su:

    WebView wv = (WebView) findViewById(R.id.webview1);

    finalString mimeType = "text/html";finalString encoding = "UTF-8";String html = "y l mt trang web n gin"+

    "

    Bn c thto ra ni dung HTML bng cch ny

    ";

    V np ln WebView nh su

    wv.loadDataWithBaseURL("", html, mimeType, encoding, "");

    Hn thn t cng c thson mt file HTML tn l Index.html v trong thmc assetsca project Android vi ni dung nh su

    y l mt file HTML n gin

  • 8/10/2019 Phan_02_Giao_dien_nguoi_dung.pdf

    94/94