Professional Documents
Culture Documents
Huong Dan Thuc Hanh Andoird PDF
Huong Dan Thuc Hanh Andoird PDF
Contents
Bi tp 1: Lm quen vi mi trng pht trin in thoi di ng .......................................................... 2
Bi tp 2: Thao tc vi Android Virtual Device v DDMS ..................................................................... 5
Bi tp 3: Cch to Android Project v tm hiu cu trc bn trong ca mt Android Project.............. 14
Bi tp 4: Cch sa mt s li thng gp trong Android Project ......................................................... 22
Bi tp 5: Tm hiu vng i ca mt ng Dng Android .................................................................... 24
Bi tp 6: Phn bit Foreground Lifetime v Visible Lifetime .............................................................. 31
Bi tp 7: Lm quen vi cc Layout trong Android ............................................................................... 40
Bi tp 8: Cc kiu lp trnh s kin trong Android ............................................................................... 51
Bi tp 9: Thc hnh v Toast Notification v Alert Dialog .................................................................. 69
Bi tp 10: S dng TextView, EditText v Button trong Android ....................................................... 72
Bi tp 11: S dng Checkbox v RadioButton trong Android ...................................................... 80
Bi tp 12: V d tng hp TextView, EditText, CheckBox, Button v ImageButton
trong Android ....................................................................................................................................... 89
Bi tp 13: Thc hnh v ListView trong Android ......................................................................... 103
Bi tp 14: Thc hnh v Custom Layout cho ListView trong Android ...................................... 125
Bi tp 15: Thc hnh v Spinner trong Android .......................................................................... 136
Bi tp 16: Kt hp Spinner vi ListView trong Android.............................................................. 139
Bi tp 17: Thc hnh v AutocompleteTextView v MultiAutocompleteTextView................. 150
Bi tp 18: Cp nht DataSource cho AutocompleteTextView lc Runtime .............................. 154
Bi tp 19: Thc hnh Gridview trong Android ............................................................................. 167
Bi tp 21: Thc hnh v Tab Selector trong Android .................................................................. 175
Bi tp 22: Thc hnh v Menu trong Android.............................................................................. 184
Bi tp 23: Thc hnh v Context Menu trong Android ............................................................... 193
Bi tp 24: Thc hnh v Intent trong Android ............................................................................. 196
Bi tp 25: Tip tc cng c kin thc Intent, v d tng hp Qun L Nhn Vin ................... 216
Bi tp 26: Dng Implicit Intent vit chng trnh gi in thoi v nhn tin SMS ........... 263
Bi tp 27: a ngn ng trong Android .......................................................................................... 274
Bi tp 28: X l tp tin trong Android ........................................................................................... 279
Bi tp 29: XML Parser trong Android ........................................................................................... 293
Bi tp 30: Thc hnh v Shared Preferences ................................................................................ 299
Bi tp 31: Cch s dng SQLite trong Android ............................................................................ 312
Bi tp 32: Tip tc cng c kin thc SQLite, v d tng hp qun l sch ............................... 320
Bi tp 33: S dng ContentProvider trong Android .................................................................... 345
Bi tp 34: a tin trnh trong Android (Multi-Threading) ......................................................... 354
Trong bi tp 1 ny, chng ta phi thc hin : Ci t c Java JDK, Android SDK, ADT plugin
for Eclipse, update Android SDK.
Cc bc chi tit:
Ti v ci t Java JDK: http://java.sun.com/javase/downloads/index.jsp (ci t ci ny
trc, nn chn bn mi nht)
Ti v ci t Android SDK: http://developer.android.com/sdk/index.html , ti gi ADT
Bundle for Windows, gi ny s cha cc thnh phn:
1.
2.
3.
-
Tham chiu Android SDK (bt buc, nu ci gi ADT Bundle for Windows trn trang
developer.android.com th n t tham chiu cho chng ta ri).
Sau khi ci t xong y (JDK, Android SDK ), ta khi ng Elipse trong gi ADT Bundle for
windows, ta c giao din nh hnh bn di:
Cc bn nhn vo hnh trn, thy c Android 4.2, API 17 hin th ra. chnh l API mi nht ca
Android, ty vo danh sch API c ti v my n s hin th ra y. Hin ti trong my ca Ti ch
c 1 API 17, nu my bn c nhiu API khc th n s lit k ra y ht.
- Nu nh my tnh ca bn c kt ni internet, th bn c th cp nht API theo cch sau:
Vo menu Windows/ Android SDK Manager (hoc bm vo biu tng trn thanh toolbar), mn
hnh Android SDK Manager s hin th ra nh bn di:
- Cc phm chc nng : (khng quan trng lm nn y Ti khng lit k ra, cc bn t m).
y Ti ch ni mt phm chc nng m Ti cho l ng lu tm, l phm chc nng cho php
quay ngang mn hnh in thoi. Bi v ngi s dng in thoi Smart Phone thng c thi quen
quay ngang, quay dc in thoi thao tc ci g . Ta phi lp trnh h tr cho xem ng v
ngang i vi mt ng dng c th no .
+ Bn nhn t hp phm Ctrl + F11 xoay ngang (bm li tr v nh c):
- mn hnh trn:
+ Mc Incoming Number Ti nhp l 5554 (port ny chnh l s in thoi ca my o)
+ Ti chn SMS v nhp vo Hell0 Ty Map
+ Nhn nt Send
>Bn quan st my o c port 5554 s nhn c tin nhn ny:
10
11
- Bn thao tc bnh thng: Thm tp tin vo in thoi tht, ly tp tin ra. Khi chy chng trnh
Android ta s chn in thoi Tht nu nh bn mun chy trn thit b tht. Eclipse cho php cu
hnh la chn cc loi My o, my tht khi chy ng dng.
**** Nh vy Ti hng dn cc bn xong phn thao tc vi AVD, trong bi tp k tip Ti
mun bn hiu c cch thc m mt ng dng Android khi trin khai n i theo ng no:
- V d:
12
13
Cch 2: Bm chut phi vo v tr bt k trong Package Explorer / Chn New / Chn Android
Project (xem hnh bn di):
- Nu nh trong Show View m khng thy Package Explorer th bn nhn mc di cng c nhn
Other, click vo n th chc chn bn trong s c Package Explorer:
15
- Sau khi chn cc thng s xong, bn nhn Next cho ti khi nt Finish xut hin (Ti khuyn l cc
bn c bm Next, ng c chnh sa g c v cc bn mi bt u lm quen vi n. Khi no quen ri
th Ta s quay li chi tit sau):
- Khi bm Finish th bn quan st Package Explorer xem cu trc bn trong ca ng dng
Android:
3) Tm hiu cu trc bn trong ca ng dng Android:
16
17
19
21
- hnh trn, nu bn chn Clean All Project , eclipse s clean ton b Project trong Package
Explorer.
22
- Nu bn chn Clean Projects selected below, eclipse s clean nhng Project m bn Checked
bn di.
b3) Bn Unchecked Build Automatically v Checked li Build Automatically trong menu
Project
Gii php 2:
- Bm chut phi vo Project / chn Android Tools / chn Fix Project Properties:
Gii php 3:
- Khai bn ko th mt s tp tin, hnh nh vo Android Project n s bo li v khng th to ra gen.
Bn hy kim tra xem c phi tn cc tp tin b Vit Hoa k t u hay khng, hay tn tp tin b
khong trng hoc l c cc k t khng hp l. Bn ch cn sa li l ht li
Gii php 4:
- n gin l tt v khi ng li Eclipse.
Trong bi tp tip theo, Ti s hng dn cc bn hiu c Vng i ca mt ng dng Android
v a ra mt s li khuyn v vic lu trng thi cng nh phc hi trng thi ca ng dng.
23
Bi tp 5: Tm hiu vng i ca mt ng
Dng Android
Trong bi tp 3 v bi tp 4 bn bit cch to mt Android Project cng nh gii quyt mt s vn
gp phi khi thc hin ng dng.
Trong bi tp 5 bn cn hiu cc khi nim sau:
1) Applications l g?
2) Activities l g?
3) Activity Stack l g?
4) Tasks l g?
5) Life Cycle States l g?
1) Applications l g?
- Bn hiu nm na nh sau: Mi mt Android Project khi bn bin dch thnh cng th s c ng
gi thnh tp tin .apk, tp tin .apk c gi l mt Application (ng dng c th no V d nh
ng dng chng tin nhn rc, ng dng tm ng i ngn nht, ng dng ng k hc phn bng
sms . )
2) Activities l g?
- Thng thng trong mt ng dng (Application) s c mt hoc nhiu Activity (bn hiu i khi
l cc mn hnh tng tc ging nh Form trong .Net).
- Mi mt Activity ny s c mt vng i ring c lp hon ton vi cc Activity khc, bn s hiu
r hn v vng i trong phn Life Cycle States. Vic hiu r vng i ca Activity l rt quan trng
trong vic x l thng tin.
- Mi mt Activity mun c triu gi trong ng dng th bt buc n phi c khai bo trong
Manifest
3) Activity Stack l g?
- Tng t nh cc ngn ng lp trnh khc, Activity Stack hot ng theo c ch LIFO (LAST IN
FIRST OUT)
-Mi mt Activity mi c m ln n s bn trn Activity c, tr v Activity th bn ch cn
nhn nt Back tr v hoc vit lnh. Tuy nhin nu bn nhn nt Home ri th s khng th
dng nt Back quay li mn hnh c c.
24
- y bn ch l c 2 kiu m Activity mi :
a) M Activity mi ln lm che khut ton b Activity c (khng nhn thy Activity c): sy ra s
kinonPause ri onStop i vi Activity c
b) M Activity mi ln lm che khut mt phn Activity c (vn nhn thy Activity c): Sy ra s
kinonPause vi Activity c.
- Khi quay tr v Activity c th sau khi thc hin xong cc hm cn thit, chc chn n phi gi
hmonResume phc hi li trng thi ng dng
- Nh vy ta thng lu li trng thi ca ng dng trong s kin onPause v c li trng thi ng
dng trong s kin onResume
4) Tasks l g?
- Bn hiu i khi Task l kh nng thc hin mt cng vic no gia cc ng dng vi nhau,
c th l cc Activity
- V d bn ang m chng trnh qun l BlackList, trong chng trnh ny cho php m danh b
a vo danh sch en. Lc chng trnh bn s gi Activity ca ng dng danh b, sau khi ly
xong li quay tr v ng dng ca bn. Nh l 2 ng dng ny hon ton khng lin quan g ti nhau
c.
1- Running (ang kch hot): Khi mn hnh l Foreground ( Activity nm trn cng ng dng v cho
php ngi s dng tng tc)
2- Paused (tm dng) : Activity b mt focus nhng m vn nhn thy c Activity ny (V d bn
m mt Activity mi ln di dng Dialog). Trng hp ny n vn c kh nng b h thng t ng
X trong tnh hung b nh qu t.
3- Stopped (dng khng phi Destroyed): Activity mt focus v khng nhn thy c (v d bn
m mt Activity mi ln m Full mn hnh chng hn). Trong trng hp ny n c th b h thng
X trong bt k tnh hung no.
*** Nh vy c Paused hay Stopped u c kh nng b Destroyed (hy) khi b nh cn cho vic
khc u tin hn.
26
- Visible Lifetime:
+ sy ra t sau khi gi onStart > cho ti lc gi onStop : trong trng hp ny TA vn c th thy
mn hnh Activity (c th tng tc khi n l foreground, khng tng tc c khi n khng phi
foreground nh gii thch trn)
- Foreground Lifetime:
+ Sy ra t khi gi onResume > cho ti lc gi onPause : trong sut thi gian ny Activity lun nm
trn cng v Ta c th tng tc c vi n
Nh vy bn hiu c vng i ca mt ng dng Android din ra nh th no.
27
}
n gin l Ti ch hin th ln xem hm no s c triu gi ng vi Life time cycle ca Activity
- By gi bn chy ng dng vo My o Android v thc hin mt s thao tc : M mt ng dng
khc, m Menu, nhn nt Back, nhn nt Home quan st hin tng bn s hiu c cch vn
hnh cc hnh ny.
- Trong bi tp tip theo Ti s lm thm mt v d v Life time cycle bn hiu r hn v n, c
bit l tn mt chng kin u l Visible Life time, u l Foreground Life time
- Bn cn phi hiu r v Life time cycle gip ch cho vic qun l ng dng
30
31
y l activity_main.xml ca MainActivity
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
xmlns:tools=http://schemas.android.com/tools
android:id=@+id/LinearLayout1
android:layout_width=match_parent
android:layout_height=match_parent
android:orientation=horizontal
tools:context=.MainActivity >
<Button
android:id=@+id/button1
android:layout_width=wrap_content
android:layout_height=wrap_content
android:layout_weight=1
android:text=SubActivity1 />
<Button
android:id=@+id/button2
android:layout_weight=1
android:layout_width=wrap_content
android:layout_height=wrap_content
android:text=SubActivity2 />
</LinearLayout>
- Ti MainActivity: Khi chn nt SubActivity1, chng trnh s m SubActivity vi dng Dialog
nh hnh bn di:
32
33
SubActivity2.class);
startActivity(intent);
}
});
}
}
Phng thc findViewById tr v View theo ng Id truyn vo, mi Control trong
Android u k tha t View, y ta p kiu v cho ng kiu Button.
Dng phng thc startActivity m mt Activity, ch l Activity ny c a vo mt
Intent vi cch khai bo nh trn.
Cch chy SubActivity1 v SubActivity2 l hon ton ging nhau. Ch khc nhau lc hin
th ln mn hnh in thoi (nh gii thch trn).
Ta s hc r hn v Intent trong phn sau, tm thi phn ny cha cn phi hiu su v n.
Ch cn bit rng chy 1 Activity no th phi tin hnh nh vy.
*** Tip tc lm vic vi class MainActivity:
Bn to Override thm mt s hm : onResume, onPause, onStop, onDestroy:
@Override
protected void onResume() {
super.onResume();
Toast.makeText
(this, onResume, Toast.LENGTH_LONG)
.show();
}
@Override
protected void onPause() {
super.onPause();
35
Toast.makeText
(this, onPause, Toast.LENGTH_LONG)
.show();
}
@Override
protected void onStop() {
super.onStop();
Toast.makeText
(this, onStop, Toast.LENGTH_LONG)
.show();
}
@Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText
(this, onDestroy, Toast.LENGTH_LONG)
.show();
}
- Bn thit k SubActivity1 sao cho ging nh hnh . Bn cn lu l mi khi chng ta to mi 1
Activity th n s t ng to ra 1 Layout cho n lun:
+ 1 Bm chut phi vo Project / chn New / chn Other
36
37
+ 4- bm Finish, v quan st ng dng s xut hin Activity v Layout cho bn. By gi bn tha h
thit k.
Trong v d ca Ti th bn ch cn ko 1 Button vo Layout ca SubActivity1
Bn t tn Button trong SubActivity1 l btntrove, cho ging vi Code tr v MainActivity di
ny:
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
public class SubActivity1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_activity1);
Button btn=(Button) findViewById(R.id.btntrove);
38
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
finish();
}
});
}
}
- Bn thy trong SubActivity1 Ti gi hm finish() khi chn Tr v MainActivity. Cng dng ca
hm finish() l tt mn hnh hin ti> nh vy n t ng m MainActivity v theo c ch
Activities Stack.
- By gi bn thc thi chng trnh v lm cc thao tc sau:
1) Chn nt SubActivity1 m Activity ny ln, quan st hin tng sy ra (ch nhng hm no
c gi)
2) Khi chn nt Tr v MainActivity, quan st hin tng sy ra (ch nhng hm no c gi)
3) Chn nt SubActivity2 m Activity ny ln, quan st hin tng sy ra (ch nhng hm no
c gi)
4) nhn nt Back ca in thoi, quan st hin tng (ch nhng hm no c gi)
*** Ti y Ti s khng gii thch th t cc hm sy ra nh th no, m dnh cho cc bn t
gii thch. Bn s thy r s khc bit trong 2 trng hp ny. V d nhin bn s t ng hiu c
Foreground Lifetime v Visible Lifetime
Cc bn c th ti coding mu
y:http://www.mediafire.com/download/7ra8h7vyttkjq6u/LearnAndroidLifetime.rar
Trong bi tp k tip Ti s hng dn cc bn cch s dng XML Layout v mt s control cn bn
thng dng cng nh cc kiu lp trnh s kin.
39
Bi tp 7: Lm quen vi cc Layout
trong Android
thit k giao din tt cho Android th trc tin cc bn phi bit s dng mt s Layout c bn
trong Android:
1) Cch to Layout v kt ni Layout vo Activity
2) Cch s dng HierarchyViewer
3) Cc Layout c bn:
FrameLayout
LinearLayout
TableLayout
RelativeLayout
AbsoluteLayout
*** ng thi bn phi bit kt hp cc Layout ny li vi nhau cho ra c giao din phc tp
nh mun.
- Ti ch nu ra mt s c im, khng th ni ht y. Cc bn s t t cp nhp sau khi quen
vi Layout.
- Trc tin bn cn bit cch to mt Layout mi v cch kt ni n vo Activity nh th no:
1) Cch to Layout v kt ni Layout vo Activity:
a) Layout mc nh u tin khi bn to mt Android Project:
- Khi bn to mt Android Project th mc nhin s c mt Activity c ch nh chy u tin khi
bn thc thi ng dng:
40
41
- Khi bn chn Android XML File th mn hnh bn di xut hin: t tn cho Layout, chn kiu
Layout ri nhn nt Finish:
42
- Khi ng chng trnh v bn thy ng dng s chy ci Layout mi ny ch khng phi Layout
c na:
43
3) Cc Layout c bn:
44
a) FrameLayout:
- L loi Layout c bn nht, c im ca n l khi gn cc control ln giao din th cc control ny
s lun c Neo gc tri trn cng mn hnh, n khng cho php chng ta thay i v tr ca cc
control theo mt Location no .
- Cc control a vo sau n s ln trn v che khut control trc (tr khi ta thit lp
transparent cho control sau):
- Bn xem on cu trc XML di ny:
<?xml version=1.0 encoding=utf-8?>
<FrameLayout android:id=@+id/mainlayout android:layout_height=fill_parent
android:layout_width=fill_parent android:orientation=vertical
xmlns:android=http://schemas.android.com/apk/res/android>
<ImageView android:layout_height=wrap_content android:layout_width=wrap_content
android:padding=5px android:src=@drawable/blue/>
<ImageView android:layout_height=wrap_content android:layout_width=wrap_content
android:padding=5px android:src=@drawable/red/>
</FrameLayout>
- Bn c th dng margin, gravity, weight h tr cho vic thit k. y Ti khng c thi gian
nhiu nn ch ni c im chnh ca LinearLayout, cc bn t tm hiu thm.
- Ta c th dng Properties h tr sn trong Eclipse thit lp cc thuc tnh cho control:
- V d nh cn l cc control trn giao din ta dng layout_gravity:
46
- V d thay i Padding (internal spacing khong cch gia ni dung bn trong so vi ng vin
ca control):
c) TableLayout
-Cho php sp cc control theo dng li (dng v ct)
- TableLayout s xem dng no c s lng control nhiu nht xc nh rng n c bao nhiu ct
(ly dng c s lng control nhiu nht lm s ct chun).
47
d) RelativeLayout:
- RelativeLayout cho php sp xp cc control theo v tr tng i gia cc control khc trn giao
din (k c control cha n). Thng n da vo Id ca cc control khc sp xp theo v tr tng
i. Do khi lm RelativeLayout bn phi ch l t Id control cho chun xc, nu sau khi
Layout xong m bn li i Id ca cc control th giao din s b xo trn (do nu i ID th phi
i lun cc tham chiu khc sao cho khp vi Id bn mi i).
- Di y l v d v cch s dng RelativeLayout (bn nhng dng t m):
48
e) AbsoluteLayout:
- Cho php thit lp cc control giao din theo v tr ty thch:
49
50
Onclick in XML
Inline anonymous listener
Activity is listener
Listener in variable
Explicit listener class
View Subclassing
- Khi nhn vo nt Tng 2 s, chng trnh s xut kt qu nh hnh bn trn : 80+33= 113
- Bn xem Layout Outline d thit k (ch l bn c th b LinearLayout1 i):
51
52
53
54
-Bn thy : Thng s bn trn chnh l ca chnh Ti, Tn Ti l Thanh, chiu cao 1.68 mt, cn
nng 58 kg. Khi Ti chn Tnh BMI th chng trnh s tnh ra c BMI ca Ti l 20.5 v chn
on l Bnh thng, tc l Ti c sc khe tt, dng ngi chun (c th l nim c ao ca mt
s cc bn trong lp).
- cc bn cng thng th Ti xin ni l do v sao Ti li vit phn mm ny lm v d minh
ha. Bi v bn gi ca Ti lun lun ch Ti gy (hay gi l X Quch g ). Ti chng mnh l
Ti c dng ngi chun khng cn chnh bng cch vit phn mm ny (cng thc theo chun Quc
T nn n l mt bng chng khng th chi ci). Ti ngh cc bn cng c th dng n chng
minh rng mnh khng b Bo Ph Cp 3.
- Quay tr li v d ,Bn xem Outline ca giao din ny di y (Ti c tnh khng cung cp source
XML nhm mc ch kch thch cc bn t tm ti):
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity
implements OnClickListener{
Button btnChandoan;
EditText editTen,editChieucao,
editCannang,editBMI,editChandoan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnChandoan=(Button) findViewById(R.id.btntinhBMI);
btnChandoan.setOnClickListener(this);
editTen=(EditText) findViewById(R.id.editten);
editChieucao=(EditText) findViewById(R.id.editchieucao);
editCannang=(EditText) findViewById(R.id.editcannang);
editBMI=(EditText) findViewById(R.id.editBMI);
editChandoan=(EditText) findViewById(R.id.editChanDoan);
}
@Override
56
}
DecimalFormat dcf=new DecimalFormat(#.0);
editBMI.setText(dcf.format(BMI));
editChandoan.setText(chandoan);
}
}
- a) Bn quan st Activity ny s implements interface OnClickListener
- b) Bn thn interface OnClickListener c m Abstract Method l onClick(View arg0) nn ta phi
Override n.
- c) Button c th hiu c s kin th Ta phi gi dng
lnh: btnChandoan.setOnClickListener(this); bn thn Activity l mt s kin nn ta dng this
truyn vo hm.
- d) Bn quan st thm Ti c s dng : DecimalFormat dcf=new DecimalFormat(#.0); Mc ch
l Ti nh dng 1 s l thp phn, bn mun 2 s l thp phn th ghi #.00 hay mun 3 th #.000
vn vn.
Bn c th load y coding mu y: http://www.mediafire.com/?71khpisxa3wmvq5
4) Listener in variable:
- Tng t nh Activity Is listener, nhng khc ch thay v implement interface cho Activity th
n li c lu tr vo mt bin c kiu Listener trong activity. Lm cch ny th ta c th chia s
chung mt bin s kin cho cc control khc nhau.
- V d bn xem hnh bn di:
58
- Giao din bn trn s c 3 button. Ta s to mt bin s kin v chia s cho 3 Button trn.
- Bn xem Outline thit k:
60
{
//Bn x l chuyn i C>F theo cng thc
}
else if(arg0==btnClear)
{
txtFar.setText();
txtCel.setText();
txtFar.requestFocus();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFar = (Button)findViewById(R.id.btnFar);
btnCel = (Button)findViewById(R.id.btnCel);
btnClear = (Button)findViewById(R.id.btnClear);
txtFar = (EditText)findViewById(R.id.txtFar);
txtCel = (EditText)findViewById(R.id.txtCel);
btnFar.setOnClickListener(myVarListener);
btnCel.setOnClickListener(myVarListener);
btnClear.setOnClickListener(myVarListener);
}
61
}
Bn t vit lnh cho 2 nt chuyn i : cch ly d liu hng dn nhng kiu lp trnh s kin
trc, bt buc bn phi ly c. Sau khi ly c th ch cn rp vo cng thc l xong.
5) Explicit listener class:
- Trng hp ny ta tch ring mt class ng vai tr l class s kin ring.
- Khi no lng coding trong ng dng khng l v phc tp th ta nn tch class s kin ring d
qun l.
Ti v d gii phng trnh bc 2, bn xem giao din bn di:
- Khi chn Tip tc, chng trnh s xa trng ton b d liu trn mn hnh ng thi focus ti
Nhp a.
- Khi chn Gii PT, chng trnh s tin hnh ly thng s a,b,c v tin hnh gii phng trnh bc
2 v cho ra kt qu nh hnh trn.
- Khi chn Thot, chng trnh s c ng li.
- Bn xem Outline di y:
62
setContentView(R.layout.activity_main);
btnTieptuc=(Button) findViewById(R.id.btntieptuc);
btnGiai=(Button) findViewById(R.id.btngiaipt);
btnThoat=(Button) findViewById(R.id.btnthoat);
btnTieptuc.setOnClickListener(new MyEvent());
btnGiai.setOnClickListener(new MyEvent());
btnThoat.setOnClickListener(new MyEvent());
edita=(EditText) findViewById(R.id.edita);
editb=(EditText) findViewById(R.id.editb);
editc=(EditText) findViewById(R.id.editc);
txtkq=(TextView) findViewById(R.id.txtkq);
}
public void giaiPtb2()
{
String sa=edita.getText()+";
String sb=editb.getText()+";
String sc=editc.getText()+";
int a=Integer.parseInt(sa);
int b=Integer.parseInt(sb);
int c=Integer.parseInt(sc);
String kq=";
DecimalFormat dcf=new DecimalFormat(#.00);
if(a==0)
{
64
if(b==0)
{
if(c==0)
kq=PT v s nghim;
else
kq=PT v nghim;
}
else
{
kq=Pt c 1 No, x=+dcf.format(-c/b);
}
}
else
{
double delta=b*b-4*a*c;
if(delta<0)
{
kq=PT v nghim;
}
else if(delta==0)
{
kq=Pt c No kp x1=x2=+dcf.format(-b/(2*a));
}
else
65
{
kq=Pt c 2 No: x1=+dcf.format((-b-Math.sqrt(delta))/(2*a))+
; x2=+dcf.format((-b-Math.sqrt(delta))/(2*a));
}
}
txtkq.setText(kq);
}
private class MyEvent implements OnClickListener
{
@Override
public void onClick(View arg0) {
if(arg0==btnTieptuc)
{
edita.setText();
editb.setText();
editc.setText();
edita.requestFocus();
}
else if(arg0.getId()==R.id.btngiaipt)
{
giaiPtb2();
}
else if(arg0.getId()==R.id.btnthoat)
{
66
finish();
}
}
}
}
- Bn quan st coding bn trn. Ti to mt lp s kin tn l MyEvent, control no mun c
gn s kin ch cn gi lnh ging nh Ti gn cho Button Gii phng trnh:
btnGiai.setOnClickListener(new MyEvent());
- Trong hm public void onClick(View arg0) . Bn l lc th Ti so snh theo Object, lc th Ti
li ly Id ra so snh. y l c ca Ti, Ti mun ni rng cc bn c th kim tra xem Button
no s c chn trn giao din bng cch so snh i tng hoc ly Id ra so snh (ty lp
trnh ca mi ngi)
- y Ti c 1 li khuyn cho cc bn l khi phi x l qu nhiu dng lnh (lnh phc tp) th bn
nn vit thnh tng hm ring, v trong hm x l s kin bn ch cn gi tn hm m thi. C th l
i vi Button Gii PT th Ti li vit v gi ring hm giaiPtb2(), cn i vi Button Tip tc v
Thot th Ti li khng cn thit vit hm v x l qu n gin.
6. View Subclassing
- K thut ny khng c ph bin cho lm. Bn ch si khi thm Control ng (lc runtime) vo
mn hnh. Ta c th dng bt k k thut no (6 cch Ti va nu) thm s kin ng cho mt
Button ng.
- cch cui cng ny th bn phi override phng trnh performClick ca chnh Button control:
68
2) Alert Dialog:
69
- Hin th v cho php ngi dng tng tc, v d bn nhn hnh Ti chp bn di, khi nhn nt
Cancel, chng trnh s hin th Alert Dialog hi xem c chc chn mun xa hay khng? Bm No
th khng, bm Yes th tt chng trnh.
ngha ca cc hm :
- setTitle : thit lp tiu cho Dialog
- setMessage: Thit lp ni dung cho Dialog
-setIcon : thit lp Icon
-setPositiveButton, setNegativeButton thit lp hin th Nt chn cho Dialog ( y bn khng
quan tm Nt chp nhn hay Nt hy n thuc PositiveButton hay NegativeButton v l ty thuc
bn chn. Ch l i s th 2 ca cc hm ny s l DialogInterface. OnClickListener ch
khng phi View. OnClickListener
- create() to Dialog
- show() hin th Dialog.
71
72
73
-Mn hnh trn cho php ta thay i thuc tnh ca control mt cch d dng.
- Tng t nh TextView, ta cng phi ly c control thng qua Id, thao tc vi d liu bn trong
EditText:
+Ly control theo Id:
EditText txtbox=(EditText) findViewById(R.id.editText1);
+Thit lp gi tr cho EditText
txtBox.setText(nhp bt c ci g vo y xem sao)
+Ly d liu bn trong EditText:
String msg=txtBox.getText().toString()
3) Button:
- Dng thit lp s kin khi ngi dng chn la.
- Cng k tha t TextView
- C 2 s kin m ngi s dng thng xuyn thao tc:
75
- By gi Ti s lm
mt v d v cch s dng 3 control ny (bn c th xem li bi tp cc kiu lp trnh s kin trong
Android):
- V d n gin l tnh cng tr nhn chia, giao din nh bn di (nhn nt no th thc hin php
ton cho nt ):
- Coding mu:
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
76
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btncong,btntru,btnnhan,btnchia;
EditText editsoa,editsob;
TextView txtkq;
OnClickListener myclick=new OnClickListener() {
@Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.btncong:
String sa=editsoa.getText()+";
String sb=editsob.getText().toString();
int a=Integer.parseInt(sa);
int b=Integer.parseInt(sb);
txtkq.setText(a+ + +b + = +(a+b));
break;
case R.id.btntru:
break;
case R.id.btnnhan:
break;
77
case R.id.btnchia:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btncong=(Button) findViewById(R.id.btncong);
btntru=(Button) findViewById(R.id.btntru);
btnnhan=(Button) findViewById(R.id.btnnhan);
btnchia=(Button) findViewById(R.id.btnchia);
editsoa=(EditText) findViewById(R.id.editsoa);
editsob=(EditText) findViewById(R.id.editsob);
txtkq=(TextView) findViewById(R.id.txtketqua);
btncong.setOnClickListener(myclick);
btntru.setOnClickListener(myclick);
btnnhan.setOnClickListener(myclick);
btnchia.setOnClickListener(myclick);
}
}
Bn hy tr li cho Ti: Hin gi on code trn Ti s dng loi S Kin no?
- Nh vy bn hiu c cch s dng TextView, EditText, Button.
78
79
-Trong coding kim tra xem Checkbox c c checked hay khng th lm nh sau:
80
82
- M t:
-
Bng cp mc nh s chn l i hc
Khi bm gi thng tin, chng trnh s hin th ton b thng tin c nhn cho ngi s dng
bit (dng Alert Dialog):
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText editTen,editCMND,editBosung;
CheckBox chkdocbao,chkdocsach,chkdoccode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTen=(EditText) findViewById(R.id.editHoten);
editCMND=(EditText) findViewById(R.id.editCMND);
editBosung=(EditText) findViewById(R.id.editBosung);
chkdocbao=(CheckBox) findViewById(R.id.chkdocbao);
84
chkdoccode=(CheckBox) findViewById(R.id.chkdoccoding);
chkdocsach=(CheckBox) findViewById(R.id.chkdocsach);
Button btn=(Button) findViewById(R.id.btnguitt);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
doShowInformation();
}
});
}
public void doShowInformation()
{
//Kim tra tn hp l
String ten=editTen.getText()+";
ten=ten.trim();
if(ten.length()<3)
{
editTen.requestFocus();
editTen.selectAll();
Toast.makeText(this, Tn phi >= 3 k t, Toast.LENGTH_LONG).show();
return;
}
//kim tra CMND hp l
85
String cmnd=editCMND.getText()+";
cmnd=cmnd.trim();
if(cmnd.length()!=9)
{
editCMND.requestFocus();
editCMND.selectAll();
Toast.makeText(this, CMND phi ng 9 k t, Toast.LENGTH_LONG).show();
return;
}
//Kim tra bng cp
String bang=";
RadioGroup group=(RadioGroup) findViewById(R.id.radioGroup1);
int id=group.getCheckedRadioButtonId();
if(id==-1)
{
Toast.makeText(this, Phi chn bng cp, Toast.LENGTH_LONG).show();
return;
}
RadioButton rad=(RadioButton) findViewById(id);
bang=rad.getText()+";
//Kim tra s thch
String sothich=";
if(chkdocbao.isChecked())
sothich+=chkdocbao.getText()+\n;
86
if(chkdocsach.isChecked())
sothich+=chkdocsach.getText()+\n;
if(chkdoccode.isChecked())
sothich+=chkdoccode.getText()+\n;
String bosung=editBosung.getText()+";
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle(Thng tin c nhn);
builder.setPositiveButton(ng, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
//to ni dung
String msg=ten+\n;
msg+= cmnd+\n;
msg+=bang+\n;
msg+=sothich;
msg+=\n;
msg+=Thng tin b sung:\n;
msg+=bosung+ \n;
msg+=;
builder.setMessage(msg);//thit lp ni dung
87
builder.create().show();//hin th Dialog
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
ch cc cch dng s kin trong on code trn.
Bn c th ti coding mu y y: http://www.mediafire.com/?wqih1ln20rilsv8
Ti y bn hiu c phnn no CheckBox v RadioButton
- Bi tp k tip Ti s lm mt v d tng hp v EditText, CheckBox, Button cng ArrayList
bn hiu thm v cc control c bn ny.
88
- M t yu cu:
Khi bm nt Tnh Thnh Tin (Tnh TT) chng trnh s tnh thnh tin bit rng mi cun
sch c n gi l 20000, nu l khch hng VIP th gim 10%
Khi bm nt Tip, chng trnh s lu thng tin ha n va tnh Thnh Tin vo danh sch,
ng thi xa trng d liu trong ha n v cho focus ti EditText Tn khch hng
Khi bm nt Thng k, chng trnh s hin th thng tin vo mc Thng tin thng k: tng s
KH, tng s KH VIP v tng doanh thu
89
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ScrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008080"
android:gravity="center"
android:text="Chng trnh tnh tin bn sch online"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFF00"
90
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
<CheckBox
android:id="@+id/chklavip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:checked="true"
android:text="Khch hng l VIP" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Thnh tin:" />
<TextView
android:id="@+id/txtthanhtien"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#C0C0C0"
android:gravity="center"
android:text="2034000"
android:textColor="#008000"
android:textSize="20sp" />
</TableRow>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btntinhtt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Tnh TT" />
<Button
android:id="@+id/btntiep"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Tip" />
<Button
android:id="@+id/btnthongke"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Thng k" />
92
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
</LinearLayout>
</TableLayout>
<TextView
android:id="@+id/TextView01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFF00"
android:text="Thng tin thng k:"
android:textSize="15sp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1" >
<TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tng s KH:" />
<EditText
android:id="@+id/edittongsokh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
android:text="3" />
</TableRow>
<TableRow
android:id="@+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tng s KH l VIP:" />
<EditText
android:id="@+id/edittongsokhlavip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
android:text="1" />
</TableRow>
93
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
<TableRow
android:id="@+id/tableRow7"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tng doanh thu:" />
<EditText
android:id="@+id/edittongdt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
android:text="2184000" />
</TableRow>
</TableLayout>
<TextView
android:id="@+id/textView9"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008080" />
<ImageButton
android:id="@+id/imgbtnthoat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:src="@drawable/exit" />
</LinearLayout>
</ScrollView>
94
package tranduythanh.com;
public class KhachHang {
private String tenKh;
private int slmua;
private boolean isVip;
public static final int GIA=20000;
public KhachHang()
{
}
public KhachHang(String tenKh,int slmua,boolean isVip)
{
this.tenKh=tenKh;
this.slmua=slmua;
this.isVip=isVip;
}
public String getTenKh() {
return tenKh;
}
public void setTenKh(String tenKh) {
this.tenKh = tenKh;
}
95
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Class DanhSachKhachHang:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package tranduythanh.com;
import java.util.ArrayList;
public class DanhSachKhachHang {
ArrayList<KhachHang>listKH=new ArrayList<KhachHang>();
public void addKhachHang(KhachHang kh)
{
listKH.add(kh);
}
public double tongDoanhThu()
96
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
{
double tien=0.0;
for(KhachHang kh:listKH)
{
tien+=kh.tinhThanhTien();
}
return tien;
}
public int tongKhachHang()
{
return listKH.size();
}
public int tongKhachHangVip()
{
int s=0;
for(KhachHang kh:listKH)
{
if(kh.isVip())
s++;
}
return s;
}
}
class MainActivity:
- Dng triu gi 2 class trn v thc thi cc nghip v:
1
2
package tranduythanh.com;
97
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btnTT,btnTiep,btnTK;
ImageButton btnThoat;
EditText editTen,editSl,editTongKh,editTongKhVip,ediTongTT;
TextView txtTT;
CheckBox chkVip;
DanhSachKhachHang danhsach=new DanhSachKhachHang();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getControls();
addEvents();
}
private void getControls()
{
btnTT=(Button) findViewById(R.id.btntinhtt);
98
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
btnTiep=(Button) findViewById(R.id.btntiep);
btnTK=(Button) findViewById(R.id.btnthongke);
btnThoat=(ImageButton) findViewById(R.id.imgbtnthoat);
editTen=(EditText) findViewById(R.id.edittenkh);
editSl=(EditText) findViewById(R.id.editsoluongsach);
editTongKh=(EditText) findViewById(R.id.edittongsokh);
editTongKhVip=(EditText)
findViewById(R.id.edittongsokhlavip);
ediTongTT=(EditText) findViewById(R.id.edittongdt);
txtTT=(TextView) findViewById(R.id.txtthanhtien);
chkVip =(CheckBox) findViewById(R.id.chklavip);
}
private void addEvents()
{
btnTT.setOnClickListener(new ProcessMyEvent());
btnTiep.setOnClickListener(new ProcessMyEvent());
btnTK.setOnClickListener(new ProcessMyEvent());
btnThoat.setOnClickListener(new ProcessMyEvent());
}
private void doTinhTien()
{
KhachHang kh=new KhachHang();
kh.setTenKh(editTen.getText()+");
kh.setSlmua(Integer.parseInt(editSl.getText()+"));
kh.setVip(chkVip.isChecked());
txtTT.setText(kh.tinhThanhTien()+");
danhsach.addKhachHang(kh);
}
99
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
- Trong MainActivity Ti c tnh tch cc nghip v ra thnh cc hm ring bit nh vy
bn d dng x l. Chng ta nn tp vit nh vy Coding c sch s, khi c li sy ra
cng gip cc bn d Fixed bug, sai hm no th sa hm m n khng b nh hng ti
cc nghip v khc.
- Bn c th load y coding mu trong link ny: http://www.mediafire.com/?lgq5g2l28xb222c
- Bn phi hiu cch lm bi tp ny ng dng cho cc phn sau.
- Hy thc hnh bi ny nhiu ln cho ti khi thc s hiu logic ca n.
- Bi tp tip theo bn s c hc v cc control nng cao trong Android, v ta s thc hnh tht k
tng control c th, u tin l ListView (control rt thng xuyn c s dng trong mt chng
trnh Android no )
102
103
- Di y l ni dung ca activity_main.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/txtselection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#dd0230dd"
android:hint="Selected person here" />
<ListView
android:id="@+id/lvperson"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
104
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
- Ti gii thch tng dng lnh bn trong code, gi Ti gii thch thm v ArrayAdapter, bn
nhn vo dng lnh 21.
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,android.R.
layout.simple_list_item_1, arr);
- D liu t Data source (arr) s c gn vo ArrayAdapter, ArrayAdapter s gn vo ListView.
- Bn nhn vo i s u tin ca constructor ArrayAdapter : this, chnh l context ca Activity hin
ti, bn c th vit MainActivity.this (nu bn vit nh th ny th bt k v tr no n cng hiu l
context ca MainActivity, do cc bn nn vit nh th ny bn c th copy paste n ti bt k
v tr no th n cng hiu)
- i s th 2 android.R.layout.simple_list_item_1 : bn android Ti t mu xanh, y chnh
l layout Listview m c Android xy dng sn, cc bi tp k tip ta s t xy dng m khng s
dng ci c sn ny. Nh vy th simple_list_item_1 lu u? v bn trong n nh th no?. N
c lu trong SDK/platforms/android-api (x)/data/res/layout/simple_list_item_1.xml. Bn c th
xem ni dung v v tr ca layout ny mt cch nhanh chng bng phm Ctrl + click chut vo
dng lnh ny, bn s thy nh bn di:
105
106
- Bc 2: Mn hnh New Android XML hin th ln, bn chn thng s ging nh hnh bn di, t
tn tp tin l mystrings.xml ri nhn nt Finish:
107
108
109
- Nh vy bn bit cch tao 1 tp tin XML v bit cch to String Array cng nh to cc phn t
nm bn trong n, By gi trong Coding ta s da vo myarray c ton b d liu t XML ra.
Bn cng ch l myarray khi bn to ra trn th n cng c to ra trong gen:
110
111
- M t:
+ Nhp d liu v nhn nt Nhp th s a vo ArrayList v hin th ln ListView
+ Nhn vo phn t no th hin th v tr v gi tr ca phn t ln TextView
+ Nhn tht lu (long click ) vo phn t no trn ListView th s xa phn t .
* To Android Project tn: Vidu_ListView_ArrayList,
Xem Layout XML ca ng dng (activity_main.xml):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="@+id/txtTen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:inputType="text"
android:layout_toRightOf="@+id/textView1"
android:ems="10" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/txtTen"
android:layout_alignBottom="@+id/txtTen"
android:layout_alignParentLeft="true"
android:background="#deb887"
android:text="Nhp tn:" />
<Button
android:id="@+id/btnNhap"
android:layout_width="wrap_content"
112
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
android:layout_height="wrap_content"
android:layout_alignRight="@+id/txtTen"
android:layout_below="@+id/txtTen"
android:layout_toRightOf="@+id/textView1"
android:textAlignment="center"
android:text="Nhp" />
<TextView
android:id="@+id/txtselection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/btnNhap"
android:background="#007380" />
<ListView
android:id="@+id/lvperson"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/txtselection"
android:background="#cccccc" >
</ListView>
</RelativeLayout>
Xem MainActivity.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package tranduythanh.com;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText txtten;
TextView txtchon;
Button btn;
ListView lv;
ArrayList<String>arrList=null;
ArrayAdapter<String> adapter=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtten=(EditText) findViewById(R.id.txtTen);
txtchon=(TextView) findViewById(R.id.txtselection);
113
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
lv=(ListView) findViewById(R.id.lvperson);
//1. To ArrayList object
arrList=new ArrayList<String>();
//2. Gn Data Source (ArrayList object) vo ArrayAdapter
adapter=new ArrayAdapter<String>
(this,
android.R.layout.simple_list_item_1,
arrList);
//3. gn Adapter vo ListView
lv.setAdapter(adapter);
btn=(Button) findViewById(R.id.btnNhap);
//4. X l s kin nhn nt Nhp
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
arrList.add(txtten.getText()+"");
adapter.notifyDataSetChanged();
}
});
//5. X l s kin chn mt phn t trong ListView
lv.setOnItemClickListener(new AdapterView
.OnItemClickListener() {
public void onItemClick(
AdapterView<?> arg0,View arg1,
int arg2,long arg3) {
txtchon.setText("position : "+ arg2+
"; value ="+arrList.get(arg2));
}
});
//6. x l s kin Long click
lv.setOnItemLongClickListener(new AdapterView
.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View
arg1,
int arg2, long arg3) {
arrList.remove(arg2);//xa phn t th arg2
adapter.notifyDataSetChanged();
return false;
}
});
}
}
114
- C 2 loi nhn vin : Nhn vin chnh thc (EmployeeFullTime ) v nhn vin thi v
(EmployeePartime).
- Mi nhn vin s c cch tnh lng khc nhau (tn phng thc tnh lng ging nhau)
- Mi nhn vin c phng thc toString xut thng tin, Ni dung xut khc nhau. Thm
FullTime ng sau Id v Name i vi nhn vin chnh thc. Thm Partime ng sau Id v Name i
vi nhn vin thi v.
- Xem giao din chng trnh:
115
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
116
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:gravity="center"
android:text="Qun l nhn vin"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TableLayout
android:layout_width="match_parent"
android:stretchColumns="*"
android:layout_height="wrap_content" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M NV:" />
<EditText
android:id="@+id/editMa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tn NV:" />
<EditText
android:id="@+id/editTen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2"
android:ems="10" />
117
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loi NV:" />
<RadioGroup
android:id="@+id/radiogroud1"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/radChinhthuc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Chnh thc" />
<RadioButton
android:id="@+id/radThoivu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Thi v" />
</RadioGroup>
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnnhap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="Nhp NV" />
</TableRow>
</TableLayout>
<TextView
android:id="@+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000" />
<ListView
118
119
120
121
122
123
124
125
android:id="@+id/lvnhanvien"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
package tranduythanh.com;
public abstract class Employee {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract double TinhLuong();
@Override
public String toString() {
// TODO Auto-generated method stub
return this.id+" - "+this.name;
}
}
- class EmployeeFullTime:
1
2
3
4
5
6
7
8
9
package tranduythanh.com;
public class EmployeeFullTime extends Employee {
@Override
public double TinhLuong() {
return 500;
}
@Override
119
10
11
12
13
14
- Class EmployeePartTime:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package tranduythanh.com;
public class EmployeePartTime extends Employee {
@Override
public double TinhLuong() {
// TODO Auto-generated method stub
return 150;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString() +" -->PartTime="+TinhLuong();
}
}
- Bn thy l 2 class dn xut t Employee Ti lm n gin l cch tnh lng khc nhau. i vi
FullTime th lng 500, Partime lng 150. v hm Xut toString() cng khc nhau 1 x.
- y ta s p dng tnh a hnh thng qua tha k, ch cn dng mt bin c kiu Employee,
nhng n c th hiu FullTime hoc Partime v xut ra thng tin ng nh mnh mong i.
- Xem class MainActivity.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package tranduythanh.com;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
public class MainActivity extends Activity {
EditText editId,editName;
Button btnNhap;
RadioGroup radgroup;
ListView lvNhanvien;
ArrayList<Employee>arrEmployee=new ArrayList<Employee>();
ArrayAdapter<Employee>adapter=null;
120
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
- Chng trnh s t ng hin th ng loi Employee m ta chn la trn giao din, y bn li
c n tp thm v tnh a hnh trong java. ng vi mi loi Employee n s t ng gi hm
toString ca loi .
V d: Nu Employee l FullTime th n gi toString ca FullTime v ngc li vi PartTime
cng vy n s ly toString ca PartTime.
- n y bn hiu tng i su v ListView, bn c th ti coding mu
y: http://www.mediafire.com/?o1we6e0mw8cpbba
5)Trng hp 5: S dng ListView nhng di dng ListActivity:
- Thay v k tha t Activity, ta s cho k tha t ListActivity.
- V d nhin cch t Id cho ListView cng c s khc bit.
- Bn xem giao din bn di:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/selection"
android:layout_width="match_parent"
122
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
android:layout_height="wrap_content"
android:background="#008000"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Khng c g c" />
</LinearLayout>
package tranduythanh.com;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends ListActivity {
TextView selection;
String arr[]={"Intel","SamSung",
"Nokia","Simen","AMD",
"KIC","ECD"};
ArrayAdapter<String >adapter=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Thit lp Data Source cho Adapter
adapter=new ArrayAdapter<String>
123
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
(this,
android.R.layout.simple_list_item_1,
arr);
//Gn Adapter vo ListView
//Nh l phi t id cho ListView theo ng quy tc
setListAdapter(adapter);
selection=(TextView) findViewById(R.id.selection);
}
@Override
protected void onListItemClick(ListView l, View v, int
position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String txt="postion = "+position +"; value ="+arr[position];
selection.setText(txt);
}
}
124
26
27
28
29
30
31
32
33
34
35
android:paddingRight="2dp"
android:paddingTop="2dp"
android:textSize="15sp" />
<CheckBox
android:id="@+id/chkitem"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:gravity="center"
android:text="Qun l nhn vin"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M NV:" />
<EditText
127
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
android:id="@+id/editMa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tn NV:" />
<EditText
android:id="@+id/editTen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gii tnh:" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/radNu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="N" />
<RadioButton
android:id="@+id/radNam"
128
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nam" />
</RadioGroup>
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnNhap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="Nhp NV" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="9"
android:background="#008000"
android:layout_marginTop="2dp"
android:text="Danh sch nhn vin:"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<ImageButton
android:id="@+id/btndelete"
android:layout_width="30dip"
android:layout_height="30dip"
android:src="@drawable/deleteicon" />
</LinearLayout>
<ListView
android:id="@+id/lvnhanvien"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
129
package tranduythanh.com;
public class Employee {
private String id;
private String name;
private boolean gender;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
@Override
public String toString() {
return this.id+"-"+this.name;
}
}
130
2) class MyArrayAdapter:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package tranduythanh.com;
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyArrayAdapter extends
ArrayAdapter<Employee>
{
Activity context=null;
ArrayList<Employee>myArray=null;
int layoutId;
/**
* Constructor ny dng khi to cc gi tr
* t MainActivity truyn vo
* @param context : l Activity t Main
* @param layoutId: L layout custom do ta to
(my_item_layout.xml)
* @param arr : Danh sch nhn vin truyn t Main
*/
public MyArrayAdapter(Activity context,
int layoutId,
ArrayList<Employee>arr){
super(context, layoutId, arr);
this.context=context;
this.layoutId=layoutId;
this.myArray=arr;
}
/**
* hm dng custom layout, ta phi override li hm ny
* t MainActivity truyn vo
* @param position : l v tr ca phn t trong danh sch
nhn vin
* @param convertView: convertView, dng n x l Item
* @param parent : Danh sch nhn vin truyn t Main
* @return View: tr v chnh convertView
*/
public View getView(int position, View convertView,
ViewGroup parent) {
/**
* bn ch l y Ti khng lm:
* if(convertView==null)
* {
* LayoutInflater inflater=
* context.getLayoutInflater();
* convertView=inflater.inflate(layoutId, null);
* }
* L do l ta phi x l xa phn t Checked, nu dng If
131
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
th
* n li checked cho cc phn t khc sau khi xa v
convertView
* lu li trng thi trc
*/
LayoutInflater inflater=
context.getLayoutInflater();
convertView=inflater.inflate(layoutId, null);
//ch l test thi, bn c th b If i
if(myArray.size()>0 && position>=0)
{
//dng lnh ly TextView ra hin th M v tn ln
final TextView txtdisplay=(TextView)
convertView.findViewById(R.id.txtitem);
//ly ra nhn vin th position
final Employee emp=myArray.get(position);
//a thng tin ln TextView
//emp.toString() s tr v Id v Name
txtdisplay.setText(emp.toString());
//ly ImageView ra thit lp hnh nh cho ng
final ImageView imgitem=(ImageView)
convertView.findViewById(R.id.imgitem);
//nu l N th ly hnh con gi
if(emp.isGender())
imgitem.setImageResource(R.drawable.girlicon);
else//nu l Nam th ly hnh con trai
imgitem.setImageResource(R.drawable.boyicon );
}
//V View l Object l dng tham chiu i tng, nn
//mi s thay i ca cc object bn trong convertView
//th n cng bit s thay i
return convertView;//tr v View ny, tc l tr lun
//v cc thng s mi m ta va thay i
}
}
package tranduythanh.com;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioGroup;
132
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
if(genderGroup.getCheckedRadioButtonId()==R.id.radNu)
gioitinh=true;
//To mt employee
Employee emp=new Employee();
emp.setId(ma);
emp.setName(ten);
emp.setGender(gioitinh);
//a vo danh sch
arrEmployee.add(emp);
//gi hm cp nht giao din
adapter.notifyDataSetChanged();
//Sau khi update th xa trng d liu v cho editma
focus
editMa.setText("");
editTen.setText("");
editMa.requestFocus();
}
//hm x l xa
public void xulyXoa()
{
//ta nn i ngc danh sch, kim tra phn t no checked
//th xa ng v tr ra khi arrEmployee
for(int i=lvNhanvien.getChildCount()-1;i>=0;i--)
{
//ly ra dng th i trong ListView
//Dng th i s c 3 phn t: ImageView, TextView,
Checkbox
View v=lvNhanvien.getChildAt(i);
//Ta ch ly CheckBox ra kim tra
CheckBox chk=(CheckBox) v.findViewById(R.id.chkitem);
//Nu n Checked th xa ra khi arrEmployee
if(chk.isChecked())
{
//xa phn t th i ra khi danh sch
arrEmployee.remove(i);
}
}
//Sau khi xa xong th gi update giao din
adapter.notifyDataSetChanged();
}
}
- By gi bn thc hin chng trnh v nhp mt s nhn vin, ri checked ri nhn xa:
134
- Bn hy tm hiu thm trn mng v cch x l cc phn t khi custom, y Ti cha x l xong:
V d bn cha th chn c vo tng phn t trong ListView (cho d bn c nghin rng ngoy
mnh ngn tay vo th n cng khng lung lay, Nu bn b CheckBox i th li c) Nn bn tm
hiu thm phn x l ny (how to selected item in custom ListView).
- Bn c th ti ton b coding mu y:http://www.mediafire.com/?16tw6xf55nivr8k
- Bn nn lm tt bi ny v n rt quan trng v hay.
- Trong cc bi tp tip theo bn s c thc hnh v Spinner, GridView, kt hp Spinner vi
ListView, kt hp Spinner vi GridView.
135
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".SpinnerActivity" >
<TextView
android:id="@+id/selection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#007380"
android:hint="selected here"
android:textColor="#ff003c" />
<Spinner
136
17
18
19
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class SpinnerActivity extends Activity {
//To mt mng d liu gi
String arr[]={
"Hng in t",
"Hng ha cht",
"Hng gia dng"};
TextView selection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
selection =(TextView) findViewById(R.id.selection);
//Ly i tng Spinner ra
Spinner spin=(Spinner) findViewById(R.id.spinner1);
//Gn Data source (arr) vo Adapter
ArrayAdapter<String> adapter=new ArrayAdapter<String>
(
this,
android.R.layout.simple_spinner_item,
arr
);
//phi gi lnh ny hin th danh sch cho Spinner
adapter.setDropDownViewResource
(android.R.layout.simple_list_item_single_choice);
//Thit lp adapter cho Spinner
spin.setAdapter(adapter);
//thit lp s kin chn phn t cho Spinner
spin.setOnItemSelectedListener(new MyProcessEvent());
}
//Class to s kin
private class MyProcessEvent implements
OnItemSelectedListener
{
//Khi c chn la th vo hm ny
137
46
47
48
49
50
51
52
53
54
55
56
57
58
138
- Chng trnh cung cp nt Nhp SP, khi ngi s dng nhp thng tin cho sn phm v nhn nt
ny th chng trnh s lu sn phm vo ng vi danh mc c chn trong Spinner ng thi cp
nht vo ListView bn di.
- Bn cn c ArrayList + ArrayAdapter cho Spinner
- V cn c ArrayList + ArrayAdapter cho ListView
-> Tc l bn phi c 2 cp (4 i tng trn)
- V d ny Ti vit thun hng i tng, v c hi ph cch mt cht so vi quy tc hng i
tng thng thng, l trong lp Sn phm Ti cho php n tham chiu trc tip ti i tng
Danh mc cha n. Nh vy th ng ti danh mc no cng c th ly c ton b danh sch sn
phm ca n, v ng ti mt sn phm bt k no cng bit c n thuc danh mc no.
- Bn xem cu trc chng trnh:
140
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:gravity="center"
android:text="Qun l sn phm"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
141
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Danh mc:" />
<Spinner
android:id="@+id/spDanhmuc"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M Sp:" />
<EditText
android:id="@+id/editId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tn Sp:" />
<EditText
142
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
android:id="@+id/editName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="Nhp SP" />
</TableRow>
</TableLayout>
<TextView
android:id="@+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:gravity="center"
android:text="Danh sch sn phm theo danh mc"
android:textColor="#FFFFFF"
android:textSize="15sp" />
<ListView
android:id="@+id/lvsanpham"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
package tranduythanh.com;
/**
* Class ny l class cha ca Product v Catalog
* v Product v Catalog u c Id v Name
* nn Ti to class ny s dng li code
* @author drthanh
143
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
*
*/
public class Goods {
//Id lu m
//Name lu tn
private String id;
private String name;
public String getid() {
return id;
}
public void setid(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Goods(String id, String name) {
super();
this.id = id;
this.name = name;
}
public Goods() {
super();
}
public String toString() {
return this.id+" - "+this.name;
}
}
- 2 class Product:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package tranduythanh.com;
/**
* Class ny lu thng tin sn phm
* n k th t Goods ly m v tn
* Ti cho n tham chiu ti Catalog
* n c th bit c n thuc danh mc no
* @author drthanh
*
*/
public class Product extends Goods{
//Ly tham chiu lp trnh cho l
private Catalog Dmuc;
public Catalog getDmuc() {
return Dmuc;
}
public void setDmuc(Catalog dmuc) {
Dmuc = dmuc;
}
144
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
- 3 class Catalog:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package tranduythanh.com;
import java.util.ArrayList;
/**
* Class dng lu tr thng tin danh mc
* v danh sch cc sn phm thuc danh mc
* @author drthanh
*
*/
public class Catalog extends Goods {
private ArrayList<Product>listSp=null;
public Catalog(String ma, String name) {
super(ma, name);
this.listSp=new ArrayList<Product>();
}
public Catalog() {
super();
this.listSp=new ArrayList<Product>();
}
/**
* kim tra sn phm tn ti trong danh mc hay cha
* @param p
* @return true nu tn ti
*/
public boolean isDuplicate(Product p)
{
for(Product p1: listSp)
{
if(p1.getid().trim().equalsIgnoreCase(p.getid().trim()))
return true;
}
return false;
}
/**
* thm 1 sn phm vo danh mc
145
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package tranduythanh.com;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
public class SpinnerAndListViewActivity extends Activity {
Spinner spinDm;
EditText editma,editten;
Button btnNhap;
ListView lvSp;
//cp i tng dng cho Spinner
ArrayList<Catalog> arraySpinner=new ArrayList<Catalog>();
146
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
ArrayAdapter<Catalog>adapterSpinner=null;
//Cp i tng dng cho ListView
ArrayList<Product>arrayListview=new ArrayList<Product>();
ArrayAdapter<Product>adapterListview=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWidgetsControl();
fakeDataCatalog();
addEventsForFormWidgets();
}
/**
* Hm ly cc control theo Id
*/
private void getWidgetsControl()
{
spinDm=(Spinner) findViewById(R.id.spDanhmuc);
editma=(EditText) findViewById(R.id.editId);
editten=(EditText) findViewById(R.id.editName);
btnNhap=(Button) findViewById(R.id.btnInput);
lvSp=(ListView) findViewById(R.id.lvsanpham);
//Cu hnh cho Spinner
adapterSpinner=new ArrayAdapter<Catalog>(this,
android.R.layout.simple_spinner_item,
arraySpinner);
adapterSpinner.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinDm.setAdapter(adapterSpinner);
//Cu hnh cho ListView
adapterListview=new ArrayAdapter<Product>(this,
android.R.layout.simple_list_item_1,
arrayListview);
lvSp.setAdapter(adapterListview);
}
/***
* Hm gi d liu, to 3 danh mc mc nh cho Spinner
*/
private void fakeDataCatalog()
{
Catalog cat1=new Catalog("1", "SamSung");
Catalog cat2=new Catalog("2", "Iphone");
Catalog cat3=new Catalog("3", "IPad");
arraySpinner.add(cat1);
arraySpinner.add(cat2);
arraySpinner.add(cat3);
adapterSpinner.notifyDataSetChanged();
}
/**
* Hm gn s kin cho Button v Spinner
*/
147
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
- Ti gii thch ngay bn trong m lnh, bn c th c v rng hiu coding Ti vit bn trn.
- Bn c th ti code mu y y: http://www.mediafire.com/?i4lev5ek8944kop
- Bi tp tip theo bn s hc AutoCompleteTextview v MultiAutoCompleteTextview. 2 control
ny bn cht cng ging nh EditText nhng n h tr ngi s dng nhp d liu c nhanh hn,
lm cho ng dng tr ln User Friendly hn, bn hy ch theo di.
149
150
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".AutoCompleteTextViewActivity" >
<TextView
android:id="@+id/selection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#5576BE"
android:text="TextView"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<AutoCompleteTextView
android:id="@+id/editauto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:completionThreshold="1"
android:ems="10" >
<requestFocus />
</AutoCompleteTextView>
<MultiAutoCompleteTextView
android:id="@+id/multiAutoCompleteTextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:completionThreshold="1"
android:ems="10" />
</LinearLayout>
package tranduythanh.com;
151
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
public class MainActivity extends Activity
implements TextWatcher /*TextWatcher x l s kin
TextChange */
{
TextView selection;
//Khai bo 2 CompleteTextView
AutoCompleteTextView singleComplete;
MultiAutoCompleteTextView multiComplete;
//Khi to mng tm Test
String arr[]={"h ni","Hu","Si gn",
"h giang","Hi an","Kin giang",
"Lm ng","Long khnh"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selection =(TextView) findViewById(R.id.selection);
//ly i tng AutoCompleteTextView ra
singleComplete=(AutoCompleteTextView)
findViewById(R.id.editauto);
//Thit lp lng nghe TextChange
singleComplete.addTextChangedListener(this);
//Thit lp ArrayADapter
singleComplete.setAdapter(
new ArrayAdapter<String>
(
this,
android.R.layout.simple_list_item_1,
arr
));
//Ly i tng MultiAutoCompleteTextView ra
multiComplete=(MultiAutoCompleteTextView)
findViewById(R.id.multiAutoCompleteTextView1);
//Thit lp ArrayADapter
multiComplete.setAdapter(
new ArrayAdapter<String>
(
this,
android.R.layout.simple_list_item_1,
arr
));
//i vi MultiAutoCompleteTextView bt buc phi gi dng
lnh ny
multiComplete.setTokenizer(new MultiAutoCompleteTextView
.CommaTokenizer());
}
//Khi chn trong AutoCompleteTextView hm ny s t ng pht
152
57
58
59
60
61
62
63
64
sinh
public void onTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
selection.setText(singleComplete.getText());
}
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence arg0, int arg1, int
arg2,
int arg3) {
}
}
153
- Bn xem mn hnh trn Ti chia ra lm 2. Bn tri cho php nhp thng tin sinh vin, bn phi cho
php hin th danh sch sinh vin nhp. Bn ch l ListView Ti lm l Custom Layout (Mi
dng Ln c 2 loi d liu: m v tn cng 1 dng. gii tnh, nm sinh, qu qun cng 1 dng v
ch nh hn c mu in nghing).
- Ngy sinh dng DatePickerDialog
- Ni sinh dng AutoCompleteTextView. Mi ln nhn Nhp Sv th chng trnh s cp nht
ng ni sinh vo DataSource ca n, ch l khng cho php trng lp. Trong cc ln nhp ni
sinh tip theo th n phi t ng lc gip ngi s dng nhp l hn.
- Ta bt u vo chi tit ng dng.
1- y l cu trc th mc trong ng dng:
154
- Di y l Outline activity_main.xml:
155
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFF0E1"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:text="Nhp Thng Tin Sinh Vin:"
android:textColor="#FFFFFF" />
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
156
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M:" />
<EditText
android:id="@+id/editMa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tn:" />
<EditText
android:id="@+id/editTen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gii tnh:" />
<CheckBox
android:id="@+id/chkGt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2"
android:text="L N" />
</TableRow>
157
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
<TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ngy sinh:" />
<EditText
android:id="@+id/editNgaySinh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="date"
android:text="25/09/1989" />
<Button
android:id="@+id/btnNgaySinh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="..." />
</TableRow>
<TableRow
android:id="@+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ni sinh:" />
<AutoCompleteTextView
android:id="@+id/autoCompleteNS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:completionThreshold="1"
android:layout_span="2"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow7"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnNhap"
158
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:gravity="center"
android:text="Nhp SV" />
</TableRow>
</TableLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#EAEAEA"
android:orientation="vertical" >
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000040"
android:text="Danh Sch Sinh Vin:"
android:textColor="#FFFFFF" />
<ListView
android:id="@+id/lvsinhvien"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
</LinearLayout>
</LinearLayout>
- cn y l ca sinhvien_item_layout.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
android:id="@+id/txtThongTinKhac"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#800000"
android:textSize="10sp"
android:textStyle="italic" />
</LinearLayout>
- class Student:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package tranduythanh.com;
import java.util.Date;
/**
* Class dng lu tr thng tin ca sinh vin
* id: M
* name: Tn
* gender: gii tnh, true l n
* birthday: lu nm sinh
* placeOfBirth: ni sinh
* @author drthanh
*
*/
public class Student {
private String id;
private String name;
private boolean gender;
private Date birthday;
private String placeOfBirth;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isGender() {
return gender;
160
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
}
public void setGender(boolean gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPlaceOfBirth() {
return placeOfBirth;
}
public void setPlaceOfBirth(String placeOfBirth) {
this.placeOfBirth = placeOfBirth;
}
public Student(String id, String name, boolean gender, Date
birthday,
String placeOfBirth) {
super();
this.id = id;
this.name = name;
this.gender = gender;
this.birthday = birthday;
this.placeOfBirth = placeOfBirth;
}
public Student() {
super();
}
}
package tranduythanh.com;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* y l class dng custom layout
* Bn c hc trc
* Class ny s ly layout: sinhvien_item_layout.xml
* @author drthanh
*
*/
public class MyArrayAdapter extends ArrayAdapter<Student> {
161
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
Activity context;
int resourceId;
ArrayList<Student>arrStudent;
public MyArrayAdapter(Activity context, int resource,
ArrayList<Student> objects) {
super(context, resource, objects);
this.context=context;
this.resourceId=resource;
this.arrStudent=objects;
}
@Override
public View getView(int position, View convertView, ViewGroup
parent) {
if(convertView==null)
{
//gn Layout vo Activity
convertView= context.getLayoutInflater().inflate(resourceId,
null);
}
//Ly Textview lu m v tn
TextView txtMaTen=(TextView)
convertView.findViewById(R.id.txtMaVaTen);
//Ly TextView lu gii tnh, nm sinh, ni sinh
TextView txtKhac=(TextView)
convertView.findViewById(R.id.txtThongTinKhac);
//Ly sinh vin th position
Student s=arrStudent.get(position);
txtMaTen.setText(s.getId()+" - "+s.getName());
//Dng SimpleDateFormat nh dng ngy thng dd/MM/YYYY ->
22/12/2012
SimpleDateFormat dft=new
SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
txtKhac.setText((s.isGender()?"N-":"Nam-")+
dft.format(s.getBirthday())+" - "+
s.getPlaceOfBirth());
return convertView;
}
}
package tranduythanh.com;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.view.Menu;
162
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView lvSinhvien;
//Cp i Custom ListView
MyArrayAdapter adapterSinhvien;
ArrayList<Student> arrSinhvien=new ArrayList<Student>();
EditText editMa,editTen,editNamsinh;
CheckBox chkGender;
Button btnNamsinh,btnNhapsv;
AutoCompleteTextView autoTextNs;
//Cp i dng cho AutoCompleteTextView
ArrayList<String>arrAuto=new ArrayList<String>();
ArrayAdapter<String>adapterAuto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFormWidgets();
addEventsForWidgets();
//fakeData();
}
/**
* hm ly cc widgets
*/
public void getFormWidgets()
{
editMa=(EditText) findViewById(R.id.editMa);
editTen=(EditText) findViewById(R.id.editTen);
editNamsinh=(EditText) findViewById(R.id.editNgaySinh);
chkGender=(CheckBox) findViewById(R.id.chkGt);
autoTextNs=(AutoCompleteTextView)
findViewById(R.id.autoCompleteNS);
btnNamsinh=(Button) findViewById(R.id.btnNgaySinh);
btnNhapsv=(Button) findViewById(R.id.btnNhap);
lvSinhvien=(ListView) findViewById(R.id.lvsinhvien);
//Gn DataSource cho Adapter ListView
adapterSinhvien=new MyArrayAdapter(this,
R.layout.sinhvien_item_layout,
arrSinhvien);
//Gn Adapter vo ListView
163
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
lvSinhvien.setAdapter(adapterSinhvien);
}
/**
* Hm thit lp s kin cho Button
*/
public void addEventsForWidgets()
{
btnNamsinh.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
processBirthday();
}
});
btnNhapsv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
processInput();
}
});
}
/**
* Hm hin th DatePickerDialog chn nm sinh
*/
public void processBirthday()
{
OnDateSetListener callBack=new OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int
arg3) {
editNamsinh.setText(arg3+"/"+arg2+"/"+arg1);
}
};
// y Ti cha x l ly ngy thng nm trn EditText a vo
DatePicker
//Bn t lm
DatePickerDialog dateDialog=new DatePickerDialog(this,
callBack, 1989, 9, 25);
dateDialog.setTitle("Birthday");
dateDialog.show();
}
/**
* Hm x l nhp d liu t giao din
*/
public void processInput()
{
String ma=editMa.getText()+"";
String ten=editTen.getText()+"";
String ns=editNamsinh.getText()+"";
String nois=autoTextNs.getText()+"";
boolean gt=chkGender.isSelected();
SimpleDateFormat dft=new
164
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
try {
Student s=new Student(ma, ten, gt, dft.parse(ns), nois);
arrSinhvien.add(s);
//Thm mi xong th gi hm di cp nhp li giao din
adapterSinhvien.notifyDataSetChanged();
//X l cho Autocomplete v ni sinh
processAutoComplete(nois);
} catch (ParseException e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
/**
* Hm x l Autocomplete Ni sinh
* @param data
*/
public void processAutoComplete(String data)
{
//Chy t u ch cui nu trng th thot khi hm
for(int i=0;i<arrAuto.size();i++)
{
String x=arrAuto.get(i);
if(x.trim().equalsIgnoreCase(data.trim()))
return;
}
//nu xung y c tc l cha tn ti-> a vo arrAuto
arrAuto.add(data);
//a vo ADapter
adapterAuto=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
arrAuto);
//a Adapter vo AutoComplete
autoTextNs.setAdapter(adapterAuto);
}
public void fakeData()
{
Student s1=new Student("1", "on i Nng", true, new
Date(1980-1900, 2, 2), "TP. H Ch Minh");
Student s2=new Student("2", "Nguyn Thy Trang", true, new
Date(1982-1900, 3, 3), "Lm ng");
Student s3=new Student("3", "Hong Vn Phc", false, new
Date(1970-1900, 4, 4), "H Ni");
Student s4=new Student("4", "inh Hng Li", false, new
Date(1972-1900, 4, 4), "Bc Giang");
Student s5=new Student("5", "Nguyn Hong Uyn", true, new
Date(1970-1900, 4, 4), "Hu");
arrSinhvien.add(s1);
arrSinhvien.add(s2);
arrSinhvien.add(s3);
arrSinhvien.add(s4);
arrSinhvien.add(s5);
adapterSinhvien.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
165
166
- Nu bn thit
lp android:numColumns=3, Tc l Gridview s ngt dng khi 3 phn t, n ch khc ch
ny, cn vic a d liu ln nh th no th n y x nh lm vi ListView.
- V d 1: Hin th vn bn ln GridView (xem hnh Ti nh s 1):
- Bn to mt Android Project tn ty thch, y Ti t tn: Vidu_Gridview_Text
- y l activity_main.xml cho ng dng:
1
2
3
4
5
6
7
8
9
10
11
12
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/selection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
167
13
14
15
16
17
18
19
20
android:background="#8A9D6F"
android:hint="Slected here" />
<GridView
android:id="@+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="3" >
</GridView>
</LinearLayout>
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
public class MainActivity extends Activity {
//Dng mng 1 chiu hoc ArrayList lu mt s d liu
String arr[]={"Ipad","Iphone","New Ipad",
"SamSung","Nokia","Sony Ericson",
"LG","Q-Mobile","HTC","Blackberry",
"G Phone","FPT - Phone","HK Phone"
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Ti tng ny dng hin th phn t c chn trong
GridView
final TextView selection=(TextView)
findViewById(R.id.selection);
final GridView gv=(GridView) findViewById(R.id.gridView1);
//Gn DataSource vo ArrayAdapter
ArrayAdapter<String>da=new ArrayAdapter<String>
(
this,
android.R.layout.simple_list_item_1,
arr
);
//gn Datasource vo GridView
gv.setAdapter(da);
//Thit lp s kin cho GridView,
gv.setOnItemClickListener(new AdapterView
.OnItemClickListener() {
168
37
38
39
40
41
42
43
44
45
169
- Bn tri l mn hnh chnh cho php hin th danh sch hnh nh vo GridView, mi ln chn vo
tng hnh trong GridView th s m hnh c chn vo mt mn hnh mi (v d nh khi chn
hnh ch Cu th n s hin th ra nh mn hnh bn phi ), nhn nt Back tr v mn hnh chnh.
- y c mt s khc bit ln l chng ta ch s dng 1 MainActivity, khng h to thm bt
k mt Activity no khc, chng ta ch thay i Layout m thi. Nn n cng l im nhn ca ng
dng.
-Hy to mt Android Project tn: Vidu_Gridview_DisplayImage v xem cu trc ca chng
trnh:
-Layout s c 2 ci: activity_main.xml l ca mn hnh chnh dng hin th danh sch hnh
nh.solo_picture.xml l dng hin th tng hnh ring l.
- To thm th mc drawble v ko th mt s hnh nh vo.
- Phn class c 2 class: MainActivity v MyImageAdapter k tha t BaseAdapter.
- By gi ta i vo chi tit ca tng ci:
- activity_main.xml:
170
- By gi ta vo cc class x l nghip v:
171
package tranduythanh.com;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
/**
* Class dng hin th tng hnh nh ring l
* @author drthanh
*
*/
public class MyImageAdapter extends BaseAdapter {
private Context mContext;
private Integer []mThumbIds;
public MyImageAdapter(Context c){
mContext=c;
}
public MyImageAdapter(Context c,Integer []arrIds){
mContext=c;
mThumbIds=arrIds;
}
public int getCount()
{
return mThumbIds.length;
}
public Object getItem(int arg0)
{
return null;
}
public long getItemId(int arg0)
{
return 0;
}
/**
* Cn override li hm ny hin th hnh nh
*/
public View getView(int arg0, View convertView, ViewGroup arg2)
{
ImageView imgView;
if(convertView==null){
imgView=new ImageView(mContext);
//can chnh li hnh cho p
imgView.setLayoutParams(new GridView.LayoutParams(85, 85));
172
46
47
48
49
50
51
52
53
54
55
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setPadding(8, 8, 8, 8);
}else{
imgView=(ImageView) convertView;
}
//ly ng v tr hnh nh c chn
//gn li ImageResource
imgView.setImageResource(mThumbIds[arg0]);
return imgView;
}
}
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity
implements OnItemClickListener
{
TextView tvMsg;
GridView gv;
TextView tvSoloMsg;
//mng lu danh sch cc id hnh nh c sn
Integer[]mThumbIds;
//Adapter cho GridView
MyImageAdapter adapter=null;
//V khng to thm 1 Activity nn ly lun 2 Id bn
solo_picture.xml
ImageView ivSoloPicture;
Button btnBack;
//Lu Bundle backup cho MainActivity
Bundle myBackupBundle;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Lu savedInstanceState trc vo myBackupBundle
myBackupBundle=savedInstanceState;
setContentView(R.layout.activity_main);
tvMsg=(TextView) findViewById(R.id.tvMsg);
//gn mng cc Id hnh nh cho mThumbIds
mThumbIds=new
Integer[]{R.drawable.image1,R.drawable.image2,
R.drawable.image3,R.drawable.image4,
R.drawable.image5,R.drawable.image6,
R.drawable.ic_launcher,R.drawable.lifecycle};
gv=(GridView) findViewById(R.id.gridView1);
//thit lp Datasource cho Adapter
173
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
174
175
- Nh hnh trn th bn thy : Tab u tin 1-CALCULATOR l giao din cho php tnh cng
tr nhn chia, Tab th 2 2-HISTORY dng hin th danh sch cc php ton thc hin.
- Bn xem cu trc tng quan ca ng dng:
176
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/tab1_layout"/>
</LinearLayout>
<LinearLayout
177
33
34
35
36
37
38
39
40
41
42
android:id="@+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="@layout/tab2_layout"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/TableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="4"
android:background="#5B8020"
android:gravity="center"
android:text="Cng tr nhn chia"
android:textColor="#FFFFFF"
android:textSize="20sp" />
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
178
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="S a:" />
<EditText
android:id="@+id/editsoa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="3"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="S b:" />
<EditText
android:id="@+id/editsob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="3"
android:ems="10"
android:inputType="number" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btncong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+" />
<Button
android:id="@+id/btntru"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-" />
<Button
android:id="@+id/btnnhan"
179
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*" />
<Button
android:id="@+id/btnchia"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/" />
</TableRow>
<TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/txtketqua"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="4"
android:background="#5B8020"
android:textColor="#FFFFFF"
android:textSize="25sp" />
</TableRow>
</TableLayout>
- V xem tip tab2_layout.xml, n gin l ch c 1 ListView cha danh sch cc php ton thc
hin bn Tab1:
1
2
3
4
5
6
7
8
9
10
11
12
13
package tranduythanh.com;
import java.util.ArrayList;
import android.os.Bundle;
180
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
//Enum thc hin php ton
enum Operator
{
Cong,//php cng
Tru,//php tr
Nhan,//php nhn
Chia//php chia
}
Button btncong,btntru,btnnhan,btnchia;
EditText editsoa,editsob;
TextView txtkq;
ListView lvHistory;
ArrayList<String>array_operator=new ArrayList<String>();
ArrayAdapter<String>adapter=null;
//Variable in listener
OnClickListener myclick=new OnClickListener() {
@Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.btncong:
{
processOperator(Operator.Cong);
}
break;
case R.id.btntru:
{
processOperator(Operator.Tru);
}
break;
case R.id.btnnhan:
{
processOperator(Operator.Nhan);
}
break;
case R.id.btnchia:
{
processOperator(Operator.Chia);
}
}
}
};
181
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
* Hm x l php ton theo operator
* @param op
*/
public void processOperator(Operator op)
{
String sa=editsoa.getText()+"";
String sb=editsob.getText().toString();
int a=Integer.parseInt(sa);
int b=Integer.parseInt(sb);
String kq="";
switch(op)
{
case Cong:
kq=a+" + "+b +" = "+(a+b);
break;
case Tru:
kq=a+" - "+b +" = "+(a-b);
break;
case Nhan:
kq=a+" * "+b +" = "+(a*b);
break;
case Chia:
if(b!=0)
kq=a+" / "+b +" = "+(a*1.0/b);
else
kq="b phai khac 0";
break;
default:
kq="Invalid operator!";
}
txtkq.setText(kq);
array_operator.add(kq);
adapter.notifyDataSetChanged();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadTabs();
doFormWidgets();
}
//Cu hnh tab
public void loadTabs()
{
//Ly Tabhost id ra trc (ci ny ca built - in android
final TabHost tab=(TabHost) findViewById
(android.R.id.tabhost);
//gi lnh setup
tab.setup();
TabHost.TabSpec spec;
//To tab1
spec=tab.newTabSpec("t1");
spec.setContent(R.id.tab1);
spec.setIndicator("1-Calculator");
182
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
tab.addTab(spec);
//To tab2
spec=tab.newTabSpec("t2");
spec.setContent(R.id.tab2);
spec.setIndicator("2-History");
tab.addTab(spec);
//Thit lp tab mc nh c chn ban u l tab 0
tab.setCurrentTab(0);
// y Ti s kin ny cc bn ty x l
//V d tab1 cha nhp thng tin xong m li qua tab 2 th
bo...
tab.setOnTabChangedListener(new
TabHost.OnTabChangeListener() {
public void onTabChanged(String arg0) {
String s="Tab tag ="+arg0 +"; index ="+
tab.getCurrentTab();
Toast.makeText(getApplicationContext(),
s, Toast.LENGTH_LONG).show();}
});
}
//Khi to cc i tng v gn ADapter cho ListView
public void doFormWidgets()
{
btncong=(Button) findViewById(R.id.btncong);
btntru=(Button) findViewById(R.id.btntru);
btnnhan=(Button) findViewById(R.id.btnnhan);
btnchia=(Button) findViewById(R.id.btnchia);
editsoa=(EditText) findViewById(R.id.editsoa);
editsob=(EditText) findViewById(R.id.editsob);
txtkq=(TextView) findViewById(R.id.txtketqua);
lvHistory=(ListView) findViewById(R.id.lvhistory);
btncong.setOnClickListener(myclick);
btntru.setOnClickListener(myclick);
btnnhan.setOnClickListener(myclick);
btnchia.setOnClickListener(myclick);
adapter=new ArrayAdapter<String>
(this,
android.R.layout.simple_list_item_1,
array_operator);
lvHistory.setAdapter(adapter);
}
}
- Nh bn thy th xml resource menu (kin trc bn trong n ta s tnh sau) ca ng dng c lu
trong th mc menu, v mc nhin n cng tn vi Layout.
184
- Bn m MainActivity ln: Thy n override phng thc onCreateOptionsMenu, dng lnh 18,
19 ca Hm ny c dng ti Menu vo ng dng khi ngi dng click vo nt Menu.
1) Cch to Menu:
a) To Menu bng XML resource:
- Gi ti s c tnh hng dn bn to 1 XML menu resource khc ng thi gip bn ti Menu
Resource mi ny vo ng dng khi nhn nt Menu cng nh vit s kin cho cc Menu Item:
+ Bm chut phi vo th mc menu/ chn New / chn Android XML File:
+Mn hnh New Android XML hin ln, ta chn Resource type l Menu ging hnh di y, t
tn cho n l mymenu ri nhn finish:
185
+ Sau khi nhn Finish, bn quan st li th mc menu ca ng dng s xut hin mymenu.xml:
+ Mn hnh trn bn
c 2 Tab: Layout v mymenu.xml, Tab Layout cho php bn to menu bng giao din,
tab mymenu.xml cho php bn to menu bng source code xml.
+ By gi ta s lm menu bng giao din, bn nhn vo nt Add pha bn trn :
186
+ Khi to mt Menu Item th c 2 phn t chnh l Id v Title (Bn xem phn Ti t mu vng).
Ta da vo Id x l coding, bn nn t Id n cho khoa hc, mang tnh gi nh. Nh bn thy ,
Ti t id cho Menu Item ny l item_xemdssv th id ny s c t ng cp nhp vo mn hnh
pha bn tri.
+ Cc thuc tnh khc bn t nghin cu trn mng, hoc khi no gp vn v n Ti s trnh by
sau.
+ C nh vy bn tun t to cho y cc Menu Item m bn mong mun.
*** Trng hp bn mun to Sub Menu Item (Menu Item cha cc Menu Item khc):
+ Ti c to thm 1 Menu Item l Xem danh sch lp, by gi Ti mun to thm 3 Sub Menu
Item cho n, bao gm Lp DHTH1A, Lp DHTH1B v Lp DHTH1C:
*Theo Hnh trn th bn chn Menu bn mun to Sub Menu cho n trc, y l item_xemlop (s
1 Ti nh du)
*Sau bn chn nt Add :
187
189
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater()
.inflate(R.menu.mymenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.item_xemdssv:
//X l xem danh sch sinh vin
break;
case R.id.item_lopdhth1a:
//x l xem thng tin lp DHTH1A
break;
case R.id.item_lopdhth1b:
break;
case R.id.item_lopdhth1c:
break;
}
return super.onOptionsItemSelected(item);
190
34
35
}
}
- Bn nhn thy y, vic to Menu lc Runtime rt d dng. Nhng nu nh bn vit code to Menu
nh vy th vic x l gp cht kh khn v bn khng bit Id ca mi Menu Item.
- Do bn nn vit li theo cch sau:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//i s 1 l nhm
//i s 2 l Id cho Menu Item
//i s 3 l th t xut hin ca Menu Item
//i s 4 l tiu cho Menu Item
int itemId=113;
menu.add(0, itemId, 0, "Menu 1");
191
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
itemId=114;
menu.add(0,itemId,1,"Menu 2");
SubMenu sub3= menu.addSubMenu("Menu 3");
itemId=115;
sub3.add(0,itemId,0,"File 1 Menu 3");
itemId=116;
sub3.add(0,itemId,1,"File 2 Menu 3");
itemId=117;
sub3.add(0,itemId,2,"File 3 Menu 3");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case 113:
//X l Menu 1
break;
case 114:
//X l Menu 2
break;
case 115:
//X l File 1 ca Menu 3
break;
case 116:
//X l File 2 ca Menu 3
break;
case 117:
//X l File 3 ca Menu 3
break;
}
return super.onOptionsItemSelected(item);
}
}
192
- hnh trn l khi Context Menu hin th ra, Ti chn Red > Mu ca Button s chuyn thnh mu
.
- Bn xem cu trc th mc ca Project ny v ni dung bn trong ca Context menu:
193
- trong strings.xml , Ti to 3 tag color : Red, Green, Blue; Ni dung bn phi dng Hex Color.
3 mu ny s c triu gi trong hm x l s kin khi ngi s dng chn tng Menu Item trong
Context Menu.
- Bn xem ni dung MainActivity.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
public class MainActivity extends Activity {
Button btnCtx;
@Override
protected void onCreate(Bundle savedInstanceState) {
194
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCtx=(Button) findViewById(R.id.btnshowcontext);
registerForContextMenu(btnCtx);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater()
.inflate(R.menu.my_context_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.itemRed:
btnCtx.setTextColor(
getResources().getColor(R.color.clrred));
break;
case R.id.itemGreen:
btnCtx.setTextColor(
getResources().getColor(R.color.clrgreen));
break;
case R.id.itemBlue:
btnCtx.setTextColor(
getResources().getColor(R.color.clrblue));
break;
}
return super.onContextItemSelected(item);
}
}
- Ti gii thch
hnh trn nh sau: T Main Activity Ti c 1 Button, khi nhn vo Button ny th s m mt Activity
khc, ti Activity mi m ny s c 1 Button cho php quay tr li MainActivity.
- Bn phi nh li vng i ca mt ng dng Android bi tp 5 v bi tp 6 lm v d ny tt
hn.
- Bn to mt Android Project c cu trc nh hnh bn di:
196
197
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#008000"
android:gravity="center"
android:text="This is main Activity"
android:textColor="#FFFF00"
android:textSize="20sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnOpenChildActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Open Child Activity" />
</LinearLayout>
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
198
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
199
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ChildActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#FFFF00"
android:gravity="center"
android:text="This is Child Activity"
android:textColor="#008040"
android:textSize="20sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnBacktoMainActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Back to Main Activity" />
</LinearLayout>
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class ChildActivity extends Activity {
200
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
- Bundle c 2 loi phng thc: putXXX dng cho bn gi i, ng vi kiu d liu no th put
ng kiu . v d trn putInt v putDouble l tng ng vi 2 loi d liu khc nhau (phi i km
vikey bn nhn c th x l ng)
- bn nhn Bundle th dng cc phng thc getXXX tng ng ly d liu theo key bn gi.
- key ny phi ging nhau cho c 2 ni. Ni nhn t key=soa th bn nhn cng phi dng key=soa.
- Ta cng c th truyn i Tng qua li gia cc Activity, cc i tng ny phi c Serialize
202
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
203
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
android:layout_gravity="center"
android:background="#008040"
android:gravity="center"
android:text="Gii phng trnh bc 1"
android:textColor="#FFFF00" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#E5E5E5"
android:text="Nhp a:" />
<EditText
android:id="@+id/txta"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#E5E5E5"
android:text="Nhp b:" />
<EditText
android:id="@+id/txtb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<Button
android:id="@+id/btnketqua"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
204
67
68
69
70
71
android:layout_column="1"
android:text="Kt qu" />
</TableRow>
</TableLayout>
</LinearLayout>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText txta,txtb;
Button btnketqua;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txta=(EditText) findViewById(R.id.txta);
txtb=(EditText) findViewById(R.id.txtb);
btnketqua=(Button) findViewById(R.id.btnketqua);
btnketqua.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//To Intent m ResultActivity
Intent myIntent=new Intent(MainActivity.this,
ResultActivity.class);
//Khai bo Bundle
Bundle bundle=new Bundle();
int a=Integer.parseInt(txta.getText().toString());
int b=Integer.parseInt(txtb.getText().toString());
//a d liu ring l vo Bundle
bundle.putInt("soa", a);
bundle.putInt("sob", b);
//a Bundle vo Intent
myIntent.putExtra("MyPackage", bundle);
//M Activity ResultActivity
startActivity(myIntent);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
205
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ResultActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Kt qu gii phng trnh bc 1" />
<TextView
android:id="@+id/txtketqua"
android:layout_width="match_parent"
android:layout_height="50sp"
android:gravity="center"
android:background="#CCFFD9"
/>
<Button
android:id="@+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Back" />
</LinearLayout>
206
package tranduythanh.com;
import java.text.DecimalFormat;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ResultActivity extends Activity {
TextView txtketqua;
Button btnBack;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
btnBack=(Button) findViewById(R.id.btnBack);
txtketqua=(TextView) findViewById(R.id.txtketqua);
//ly intent gi Activity ny
Intent callerIntent=getIntent();
//c intent ri th ly Bundle da vo MyPackage
Bundle packageFromCaller=
callerIntent.getBundleExtra("MyPackage");
//C Bundle ri th ly cc thng s da vo soa, sob
int a=packageFromCaller.getInt("soa");
int b=packageFromCaller.getInt("sob");
//tin hnh x l
giaipt(a, b);
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
public void giaipt(int a,int b)
{
String kq="";
if(a==0 && b==0)
{
kq="V s nghim";
}
else if(a==0 && b!=0)
{
kq="V nghim";
}
else
{
DecimalFormat dcf=new DecimalFormat("0.##");
kq=dcf.format(-b*1.0/a);
}
txtketqua.setText(kq);
207
53
54
55
56
57
58
59
60
61
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if
it is present.
getMenuInflater().inflate(R.menu.activity_result, menu);
return true;
}
}
-Bn xem dng lnh 22: Intent callerIntent=getIntent(); lnh ny cho php ly Intent start Activity
ny. Tc l ly Intent m ta khai bo bn MainActivity start ResultActivity.
- C c Intent ny ri th mi th bn lm nh Ti gii thch trong Coding trn.
- Bn c th ti coding mu y:http://www.mediafire.com/?vb8ddcoos7dupv7
V d 3: M mt Activity khc ng thi truyn d liu qua v x l kt qu tr v.
- V d ny bn s bit cch x l kt qu tr v nh th no.
- Bn xem hnh minh ha:
- V phi thm hm x l kt qu tr v:
208
- Ti lm v d sau bn d hiu:
- Chng trnh n gin l MainActivity s c 1 Button v ListView nh hnh bn di:
- Khi nhn M Activity nhp d liu, chng trnh s m Activity mi di dng Dialog:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/btnopenactivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="M Activity Nhp D Liu" />
<ListView
android:id="@+id/lvdata"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
210
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".InputDataActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nhp s:" />
<EditText
android:id="@+id/editNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnSave1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Lu Bnh Phng" />
<Button
android:id="@+id/btnSave2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Lu S gc" />
</LinearLayout>
</LinearLayout>
211
package tranduythanh.com;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
212
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import android.widget.ListView;
public class MainActivity extends Activity {
public static final int REQUEST_CODE_INPUT=113;
public static final int RESULT_CODE_SAVE1=115;
public static final int RESULT_CODE_SAVE2=116;
Button btnInputData;
ListView lvData;
ArrayList<Integer>arrData=new ArrayList<Integer>();
ArrayAdapter<Integer>adapter=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInputData =(Button) findViewById(R.id.btnopenactivity);
btnInputData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//M Activity vi REQUEST_CODE_INPUT
Intent intent=new Intent(MainActivity.this,
InputDataActivity.class);
//gi startActivityForResult
startActivityForResult(intent, REQUEST_CODE_INPUT);
}
});
//on code di ny hc nhiu ri, ko ni li
lvData=(ListView) findViewById(R.id.lvdata);
adapter=new ArrayAdapter<Integer>
(this,
android.R.layout.simple_list_item_1,
arrData);
lvData.setAdapter(adapter);
}
/**
* X l kt qu tr v y
*/
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//Kim tra c ng requestCode =REQUEST_CODE_INPUT hay khng
//V ta c th m Activity vi nhng RequestCode khc nhau
if(requestCode==REQUEST_CODE_INPUT)
{
//Kim tr ResultCode tr v, ci ny bn InputDataActivity
truyn v
//c n ri th x l tr ln thng thng
switch(resultCode)
{
case RESULT_CODE_SAVE1:
//gi tr t InputDataActivity
int v1= data.getIntExtra("data", 0);
213
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
arrData.add(v1*v1);
adapter.notifyDataSetChanged();
break;
case RESULT_CODE_SAVE2:
//gi tr t InputDataActivity
int v2= data.getIntExtra("data", 0);
arrData.add(v2);
adapter.notifyDataSetChanged();
break;
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class InputDataActivity extends Activity {
Button btnSave1,btnSave2;
EditText editNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input_data);
btnSave1=(Button) findViewById(R.id.btnSave1);
btnSave2=(Button) findViewById(R.id.btnSave2);
btnSave1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//Gi thng ip l lu bnh phng
sendToMain(MainActivity.RESULT_CODE_SAVE1);
214
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
}
});
editNumber=(EditText) findViewById(R.id.editNumber);
btnSave2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//Gi thng ip l lu s gc
sendToMain(MainActivity.RESULT_CODE_SAVE2);
}
});
}
/**
* hm x l gi kt qu v mainactivity
* khi hm ny c gi th lp tc onActivityResult
* MainActivity s sy ra em theo ResultCode v Intent
* @param resultcode
*/
public void sendToMain(int resultcode)
{
Intent intent=getIntent();
int value= Integer.parseInt(editNumber.getText()+"");
intent.putExtra("data", value);
setResult(resultcode, intent);
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.activity_input_data, menu);
return true;
}
}
- Bn c th ti code mu y y: http://www.mediafire.com/?d8if4q9asgso18q
- M t chng trnh:
+ Chng trnh cho php qun l nhn vin + phng ban.
+ Mi phng ban s c nhiu nhn vin, phng ban cn lu tr (m phng ban, tn phng ban)
+ Mt phng ban s c Trng phng v Ph phng. Trng phng th ch c 1, ph phng th s
lng khng gii hn (hoc khng c)
+ Thng tin nhn vin : M nhn vin, tn nhn vin, gii tnh (nam, n), chc v (trng phng,
ph phng, nhn vin)
+ Chng trnh cho php:
- Khi nhn tht lu vo mt phng ban no , v d trng hp trn l phng K Thut, chng
trnh s hin th context Menu c 4 chc nng:
1. Thm nhn vin
2. Xem danh sch nhn vin
3. Lp trng/ ph phng
4. v xa phng ban.
- ng vi mi chc nng ta c:
1. Thm nhn vin:
- Mc nh mi mt nhn vin mi c to ra th ch c chc v l Nhn Vin (khng c chc qun
l):
218
- Nh bn thy . Mn hnh xem danh sch nhn vin c cc chc nng sau:
219
220
- Thng tin ca nhn vin Trn o c s c hin th nh trn. M nhn vin s cm thay i,
cn cc chc nng khc l y x nh trong mn hnh thm mi nhn vin.
- Trong trng hp ny Ti sa Trn o c thnh Trn Th v nhn nt Lu nhn vin th
mn hnh ny ng li tr v mn hnh xem danh sch, bn quan st s thay i nh sau:
- Sau khi chn phng ban chuyn, nhn nt c hnh Apply, chng trnh s quay li mn hnh
xem danh sch nhn vin, lc ny Bn khng cn thy nhn vin Trn Th na, bi v nhn vin ny
c chuyn qua phng dch v:
221
- Bn c th kim tra li bng cch bm nt Back tr v mn hnh chnh, trong mn hnh chnh
s xut hin 1 nhn vin m ta va chuyn:
3. Lp trng/ ph phng:
222
- by gi ta qua chc nng Lp trng / ph phng cho mi phng ban (ti mn hnh chnh).
- Khi context Menu hin th ln th ta chn Lp trng. ph phng:
- V d, by gi Ti nhn tht lu vo phng ban Truyn Thng, sau Ti thit lp trng ph
phng li cho phng ban ny, xem giao din bn di:
- Sau khi chn lp trng/ ph phng, th chng trnh hin th mn hnh thit lp nh bn di:
223
224
225
package tranduythanh.com.model;
/**
* Enum ny thit lp chc v cho nhn vin
* @author drthanh
*
*/
public enum ChucVu {
//Mun gn c nh th ny: TruongPhong("Trng Phng")
//th phi c constructor ChucVu(String cv)
TruongPhong("Trng Phng"),
PhoPhong("Ph Phng"),
NhanVien("Nhn Vin");
private String cv;
ChucVu(String cv)
{
this.cv=cv;
}
public String getChucVu()
{
return this.cv;
}
}
- Coding Infor.java:
1
2
3
4
5
6
package tranduythanh.com.model;
import java.io.Serializable;
/**
* Class ny lu m v tn l class cha ca NhanVien
* v PhongBan. V c nhn vin hay phng ban u c m v
226
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
tn
* @author drthanh
*
*/
public class Infor implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String ma;
private String ten;
public Infor(String ma, String ten) {
super();
this.ma = ma;
this.ten = ten;
}
public Infor() {
super();
}
public String getMa() {
return ma;
}
public void setMa(String ma) {
this.ma = ma;
}
public String getTen() {
return ten;
}
public void setTen(String ten) {
this.ten = ten;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.ma+" - "+this.ten;
}
}
- Coding NhanVien.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package tranduythanh.com.model;
import java.io.Serializable;
/**
* Class lu tr thng tin nhn vin
* @author drthanh
*
*/
public class NhanVien extends Infor implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private boolean gioitinh;
private ChucVu chucvu;
227
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
- Coding PhongBan.java:
1
2
3
4
5
6
7
8
9
10
11
package tranduythanh.com.model;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Class lu thng tin phng ban
* @author drthanh
*
*/
public class PhongBan extends Infor implements Serializable{
228
- 2 Adapter ny dng custom layout cho danh sch Phng ban v danh sch nhn vin.
- Ch l c 2 Adapter ny u dng chung 1 Layout tn layout_item_custom.xml:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/imgview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/txtShortInfor"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:id="@+id/txtDetailInfor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000080"
android:textSize="10sp"
android:textStyle="italic" />
</LinearLayout>
- By gi ta xem cch custom layout thng qua ADapter (phn customlayout Ti hng dn cc
bi tp trc, bn t xem li):
- Coding PhongBanAdapter.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package tranduythanh.com.adapter;
import java.util.ArrayList;
import tranduythanh.com.activity.R;
import tranduythanh.com.model.NhanVien;
import tranduythanh.com.model.PhongBan;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* Class ny dng custom layout cho Danh sch phng ban
* @author drthanh
*
231
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
*/
public class PhongBanAdapter extends ArrayAdapter<PhongBan> {
Activity context;
int layoutId;
ArrayList<PhongBan> arrPhongBan;
public PhongBanAdapter(Activity context, int
textViewResourceId,
ArrayList<PhongBan> objects) {
super(context, textViewResourceId, objects);
this.context=context;
this.layoutId=textViewResourceId;
this.arrPhongBan=objects;
}
@Override
public View getView(int position, View convertView, ViewGroup
parent) {
//gn layout vo coding
convertView=context.getLayoutInflater().inflate(layoutId,
null);
//ly cc control ra theo id
TextView txtpb= (TextView)
convertView.findViewById(R.id.txtShortInfor);
TextView txtmotapb= (TextView)
convertView.findViewById(R.id.txtDetailInfor);
//Ly phng ban th position
PhongBan pb=arrPhongBan.get(position);
txtpb.setText(pb.toString());
/**
* Cc Dng lnh di ny kim tra Trng phng, ph phng
*/
String strMota="";
String tp="Trng Phng: [Cha c]";
NhanVien nv=pb.getTruongPhong();
if(nv!=null)
{
tp="Trng Phng: ["+nv.getTen()+"]";
}
ArrayList<NhanVien> dsPp=pb.getPhoPhong();
String pp="Ph phng: [Cha c]";
if(dsPp.size()>0)
{
pp="Ph phng:\n";
for(int i=0;i<dsPp.size();i++)
{
pp+=(i+1)+". "+dsPp.get(i).getTen()+"\n";
}
}
strMota=tp+"\n"+pp;
//gn thng tin cho phn chi tit
txtmotapb.setText(strMota);
return convertView;
}
}
232
package tranduythanh.com.adapter;
import java.util.ArrayList;
import tranduythanh.com.activity.R;
import tranduythanh.com.model.NhanVien;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Class to customlayout cho danh sch nhn vin
* ImageVIew hin th hnh nh theo gii tnh
* @author drthanh
*
*/
public class NhanVienAdapter extends ArrayAdapter<NhanVien> {
Activity context;
int layoutId;
ArrayList<NhanVien> arrNhanVien;
public NhanVienAdapter(Activity context, int
textViewResourceId,
ArrayList<NhanVien> objects) {
super(context, textViewResourceId, objects);
this.context=context;
this.layoutId=textViewResourceId;
this.arrNhanVien=objects;
}
@Override
public View getView(int position, View convertView, ViewGroup
parent) {
//gn XML layout vo coding
convertView=context.getLayoutInflater().inflate(layoutId,
null);
//ly cc control ra
TextView txtnv= (TextView)
convertView.findViewById(R.id.txtShortInfor);
TextView txtmotanv= (TextView)
convertView.findViewById(R.id.txtDetailInfor);
ImageView img=(ImageView)
convertView.findViewById(R.id.imgview);
//ly nhn vin th position
NhanVien nv=arrNhanVien.get(position);
txtnv.setText(nv.toString());
String strMota="";
String cv="Chc v: "+nv.getChucvu().getChucVu();
String gt="Gii tnh: "+(nv.isGioitinh()?"N":"Nam");
//Kim tra gii tnh gn cho ng hnh i din
img.setImageResource(R.drawable.girlicon);
233
if(!nv.isGioitinh())
img.setImageResource(R.drawable.boyicon);
strMota=cv+"\n"+gt;
txtmotanv.setText(strMota);
return convertView;
}
52
53
54
}
- By gi ta qua package tranduythanh.com.activity:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
234
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:gravity="center"
android:text="Chng trnh qun l nhn vin"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M Phng Ban:" />
<EditText
android:id="@+id/editmapb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tn Phng Ban:" />
<EditText
235
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
android:id="@+id/editTenpb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnluupb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="Lu Phng Ban" />
</TableRow>
</TableLayout>
<TextView
android:id="@+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:text="Danh sch phng ban"
android:textColor="#FFFFFF"
android:textSize="15sp" />
<ListView
android:id="@+id/lvphongban"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
package tranduythanh.com.activity;
import java.util.ArrayList;
import tranduythanh.com.activity.R;
import tranduythanh.com.adapter.PhongBanAdapter;
import tranduythanh.com.model.ChucVu;
import tranduythanh.com.model.NhanVien;
import tranduythanh.com.model.PhongBan;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
236
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
/**
* Class MainActivity ca ng dng
* @author drthanh
*
*/
public class MainActivity extends Activity {
//Khai bo cc Request + Result code x l Intent for
result
public static final int MO_ACTIVITY_THEM_NHAN_VIEN=1;
public static final int MO_ACTIVITY_SUA_NHAN_VIEN=2;
public static final int THEM_NHAN_VIEN_THANHCONG=3;
public static final int SUA_NHAN_VIEN_THANHCONG=4;
public static final int XEM_DS_NHAN_VIEN=5;
public static final int CAPNHAT_DS_NHAN_VIEN_THANHCONG=6;
public static final int MO_ACTIVITY_THIET_LAP_TP_PP=7;
public static final int THIET_LAP_TP_PP_THANHCONG=8;
public static final int MO_ACTIVITY_CHUYENPHONG=9;
public static final int CHUYENPHONG_THANHCONG=10;
private Button btnLuuPb;
private EditText editMapb,editTenpb;
private ListView lvpb;
private static ArrayList<PhongBan>arrPhongBan=new
ArrayList<PhongBan>();
// y dng PhongBanAdapter
private PhongBanAdapter adapterPb=null;
private PhongBan pbSelected=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFormWidgets();
addEvents();
fakeData();
}
/**
* Hm ny dng ti d liu tm ( phi nhp mi tay)
* Ti dng hm ny v d cho l
* bn c th xa n i (ni chung v thng v pht)
*/
public void fakeData()
{
NhanVien nv=null;
PhongBan pb=new PhongBan("pb1", "K thut");
237
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
break;
case R.id.mnudanhsachnv:
doDanhSachNhanVien();
break;
case R.id.mnutruongphong:
doThietLapLanhDao();
break;
case R.id.mnuxoapb:
doXoaPhongBan();
break;
}
return super.onContextItemSelected(item);
}
/**
* khi chn menu Thm nhn vin, n thun ch l hin th
* mn hn thm nhn vin (vi dng Dialog)
* nh l dng startActivityForResult
* do ta lng nghe kt qu ti hm onActivityResult
*/
public void doThemNhanVien()
{
Intent i=new Intent(this, ThemNhanVienActivity.class);
startActivityForResult(i, MO_ACTIVITY_THEM_NHAN_VIEN);
}
/**
* hm onActivityResult x l kt qu tr v
* sau khi gi startActivityForResult kt thc
*/
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//mn hnh thm mi nhn vin tr kt qu v
if(resultCode==THEM_NHAN_VIEN_THANHCONG)
{
//Cch ly d liu hc ri, ko ni li
Bundle bundle= data.getBundleExtra("DATA");
NhanVien nv= (NhanVien) bundle.getSerializable("NHANVIEN");
pbSelected.themNv(nv);
adapterPb.notifyDataSetChanged();
}
//Mn hnh thit lp lnh o/ cp nht danh sch tr
//kt qu v
else if(resultCode==THIET_LAP_TP_PP_THANHCONG||
resultCode==CAPNHAT_DS_NHAN_VIEN_THANHCONG)
{
//Cch ly d liu hc ri, ko ni li
Bundle bundle= data.getBundleExtra("DATA");
PhongBan pb= (PhongBan) bundle.getSerializable("PHONGBAN");
//n thun l xa danh sch c
pbSelected.getListNhanVien().clear();
//ri cp nht li ton b danh sch mi
//sinh vin c th chn gii php thng minh hn
//tc l phn t no b nh hng th x l phn t
240
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
pbSelected.getListNhanVien().addAll(pb.getListNhanVien());
adapterPb.notifyDataSetChanged();
}
}
/**
* hm cho php danh xem danh sch nhn vin ca phng
* ban ang chn, n thun l m DanhSachNhanVienActivity
* v truyn phng ban qua -->ton b danh sch nhn vin
* s c hin th trong DanhSachNhanVienActivity
*/
public void doDanhSachNhanVien()
{
Intent i=new Intent(this, DanhSachNhanVienActivity.class);
Bundle bundle=new Bundle();
bundle.putSerializable("PHONGBAN", pbSelected);
i.putExtra("DATA", bundle);
startActivityForResult(i, XEM_DS_NHAN_VIEN);
}
/**
* hm cho php m mn hnh thit lp lnh o phng ban
* Trng phng v ph phng
* ThietLapTruongPhongActivity s c 2 ListView
* - Listview 1 hin th dang radiobutton ch chn 1 trng
phng
* - ListView 2 hin th dng Checkbox cho php chn nhiu ph
phng
*/
public void doThietLapLanhDao()
{
Intent i=new Intent(this, ThietLapTruongPhongActivity.class);
Bundle bundle=new Bundle();
bundle.putSerializable("PHONGBAN", pbSelected);
i.putExtra("DATA", bundle);
startActivityForResult(i, MO_ACTIVITY_THIET_LAP_TP_PP);
}
/**
* hm cho php xa phng ban ang chn
*/
public void doXoaPhongBan()
{
AlertDialog.Builder builder=new AlertDialog.Builder (this);
builder.setTitle("Hi xa");
builder.setMessage("Bn c chc chn mun xa
["+pbSelected.getTen()+"]");
builder.setIcon(android.R.drawable.ic_input_delete);
builder.setNegativeButton("Khng", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
arg0.cancel();
}
});
builder.setPositiveButton("", new
241
284
285
286
287
288
289
290
291
292
293
294
295
296
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
arrPhongBan.remove(pbSelected);
adapterPb.notifyDataSetChanged();
}
});
builder.show();
}
/**
* Ti c tnh cung cp hm ny cc Activity khc u
* c th truy sut c danh sch phng ban tng th
* @return
*/
public static ArrayList<PhongBan> getListPhongBan()
{
return arrPhongBan;
}
}
- Ta qua mn hnh thm nhn vin. Ch l mn hnh ny bn phi cu hnh m dng Dialog.
- xem layout:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ThemNhanVienActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:text="Thng Tin Nhn Vin"
android:textColor="#FFFFFF"
android:textSize="15sp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M NV:" />
<EditText
android:id="@+id/editMaNV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
243
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
android:id="@+id/btnluunv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lu nhn vin" />
</TableRow>
</TableLayout>
</LinearLayout>
package tranduythanh.com.activity;
import tranduythanh.com.activity.R;
import tranduythanh.com.model.ChucVu;
import tranduythanh.com.model.NhanVien;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
/**
* class ny cho php thm mi mt nhn vin vo
* Phng ban ang chn
* @author drthanh
*
*/
public class ThemNhanVienActivity extends Activity {
private Button btnXoaTrang,btnLuuNhanVien;
private EditText editManv,editTenNv;
private RadioButton radNam;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_them_nhan_vien);
getFormWidgets();
addEvents();
}
/**
* hm ly cc control theo id
*/
public void getFormWidgets()
{
btnXoaTrang=(Button) findViewById(R.id.btnxoatrang);
btnLuuNhanVien=(Button) findViewById(R.id.btnluunv);
editManv=(EditText) findViewById(R.id.editMaNV);
editTenNv=(EditText) findViewById(R.id.editTenNV);
245
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
radNam=(RadioButton) findViewById(R.id.radNam);
}
/**
* hm gn s kin
*/
public void addEvents()
{
btnXoaTrang.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
doXoaTrang();
}
});
btnLuuNhanVien.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
doLuuNhanVien();
}
});
}
/**
* n thun l xa trng d liu ca cc control
* ri focus ti m
*/
public void doXoaTrang()
{
editManv.setText("");
editTenNv.setText("");
editManv.requestFocus();
}
/**
* hm lu nhn vin theo phng ban
* truyn nhn vin qua MainActivity
* MainActivity c nhim v ly c nhn vin ny
* v a h vo phng ban chn lc ny
*/
public void doLuuNhanVien()
{
NhanVien nv=new NhanVien();
nv.setMa(editManv.getText()+"");
nv.setTen(editTenNv.getText()+"");
nv.setChucvu(ChucVu.NhanVien);
nv.setGioitinh(!radNam.isChecked());
Intent i=getIntent();
Bundle bundle=new Bundle();
bundle.putSerializable("NHANVIEN", nv);
i.putExtra("DATA", bundle);
setResult(MainActivity.THEM_NHAN_VIEN_THANHCONG, i);
finish();
}
}
246
96
- Tip tc ta xem mn hnh Xem danh sch nhn vin:
- bn xem outline:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".DanhSachNhanVienActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageButton
android:id="@+id/btnback"
android:layout_width="16dp"
android:layout_height="16dp"
android:contentDescription="TODO"
android:src="@drawable/back" />
<TextView
android:id="@+id/txtmsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:textColor="#FFFFFF" />
247
26
27
28
29
30
31
32
33
34
35
</LinearLayout>
<ListView
android:id="@+id/lvnhanvien"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
package tranduythanh.com.activity;
import java.util.ArrayList;
import tranduythanh.com.activity.R;
import tranduythanh.com.adapter.NhanVienAdapter;
import tranduythanh.com.model.NhanVien;
import tranduythanh.com.model.PhongBan;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
/**
* class ny dng hin th danh sch nhn vin
* Class ny cng phc tp khng km MainActivity
* nh l dng custom layout
* - Hin th danh sch
* - cho php chnh sa
* - cho php chuyn phng ban
* - cho php xa nhn vin
* @author drthanh
248
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
*
*/
public class DanhSachNhanVienActivity extends Activity {
TextView txtmsg;
ImageButton btnback;
ListView lvNhanvien;
ArrayList<NhanVien> arrNhanvien=null;
//Nhn vin Adapter hin th thng tin
//v chi tit : chc v, gii tnh
NhanVienAdapter adapter=null;
PhongBan pb=null;
private NhanVien nvSelected=null;
private int position=-1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_danh_sach_nhan_vien);
txtmsg=(TextView) findViewById(R.id.txtmsg);
btnback=(ImageButton) findViewById(R.id.btnback);
lvNhanvien=(ListView) findViewById(R.id.lvnhanvien);
getDataFromMain();
addEvents();
registerForContextMenu(lvNhanvien);
}
/**
* hm ly gi tr t MainActivity
* s truyn phng ban qua
* bn ny ly phng ban v da vo phng ban ny
* ly ra danh sch nhn vin
*/
public void getDataFromMain()
{
Intent i=getIntent();
Bundle b=i.getBundleExtra("DATA");
pb= (PhongBan) b.getSerializable("PHONGBAN");
arrNhanvien=pb.getListNhanVien();
adapter=new NhanVienAdapter(this,
R.layout.layout_item_custom,
arrNhanvien);
lvNhanvien.setAdapter(adapter);
txtmsg.setText("DS nhn vin ["+pb.getTen()+"]");
}
/**
* hm gn s kin ( qu quen thuc ri)
* c lu vt li nhn vin va chn x l
* cho contextmenu
*/
public void addEvents()
{
btnback.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
doUpdateToMain();
249
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
}
});
lvNhanvien.setOnItemLongClickListener(new
OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View
arg1,
int arg2, long arg3) {
nvSelected=arrNhanvien.get(arg2);
position=arg2;
return false;
}
});
}
/**
* hm gn context menu( qu quen thuc)
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.contextmenu_nhanvien,
menu);
}
/**
* hm x l s kin chn menuitem ( quen thuc qu)
*/
@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId())
{
case R.id.mnusuanv:
doSuaNhanVien();
break;
case R.id.mnuchuyenpb:
doChuyenPhongBan();
break;
case R.id.mnuxoanv:
doXoaNhanVien();
break;
}
return super.onContextItemSelected(item);
}
/**
* hm onActivityResult x l kt qu tr v
* cho trng hp x dng COntext Menu m cc
* Activity khc
*/
@Override
protected void onActivityResult(int requestCode, int
resultCode, Intent data) {
250
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package tranduythanh.com.activity;
import tranduythanh.com.model.NhanVien;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
252
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* class ny cho php sa nhn vin c chn trong
Danhsachnhanvien
* s dng chung Layout vi Thm nhn vin
* Khng cho sa m s nhn vin
* khi bm lu th cp nht li (rt n gin)
* @author drthanh
*
*/
public class SuaNhanVienActivity extends Activity{
EditText editMa,editTen;
RadioButton radNam;
Button btnClear,btnSave;
NhanVien nv=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_them_nhan_vien);
getFormWidgets();
getDefaultData();
addEvents();
}
/**
* hm ly cc control theo id
*/
public void getFormWidgets()
{
editMa=(EditText) findViewById(R.id.editMaNV);
editTen=(EditText) findViewById(R.id.editTenNV);
radNam=(RadioButton) findViewById(R.id.radNam);
editMa.setEnabled(false);
editTen.requestFocus();
btnClear=(Button) findViewById(R.id.btnxoatrang);
btnSave=(Button) findViewById(R.id.btnluunv);
}
/**
* hm ly gi tr t DanhSachNhanVienActivity truyn qua
* hin th
*/
public void getDefaultData()
{
Intent i =getIntent();
Bundle b=i.getBundleExtra("DATA");
nv=(NhanVien) b.getSerializable("NHANVIEN");
editMa.setText(nv.getMa());
editTen.setText(nv.getTen());
radNam.setChecked(true);
if(nv.isGioitinh())
radNam.setChecked(false);
}
public void addEvents()
{
btnClear.setOnClickListener(new OnClickListener() {
253
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
editTen.setText("");
editTen.requestFocus();
}
});
/**
* bm lu th ng ca s sa ny
* v truyn d liu qua mn hnh cha n t cp nht
*/
btnSave.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i =getIntent();
nv.setTen(editTen.getText()+"");
nv.setGioitinh(!radNam.isChecked());
Bundle b=new Bundle();
b.putSerializable("NHANVIEN", nv);
i.putExtra("DATA", b);
setResult(MainActivity.SUA_NHAN_VIEN_THANHCONG, i);
finish();
}
});
}
}
- Mn hnh ny l mn hnh con ca mn hnh Xem danh sch nhn nhin (lc dng Context Menu).
254
- Khi chn nhn vin no th s tin hnh m mn hnh chuyn phng ban cho nhn vin .
- xem XML Resource:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ChuyenPhongBanActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:text="Chn phng ban chuyn"
android:textColor="#FFFFFF"
android:textSize="15sp" />
<ListView
android:id="@+id/lvphongban"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3" >
</ListView>
<ImageButton
android:id="@+id/imgapply"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_gravity="center"
android:contentDescription="Thit lp"
android:src="@drawable/apply" />
</LinearLayout>
package tranduythanh.com.activity;
import java.util.ArrayList;
import tranduythanh.com.model.NhanVien;
import tranduythanh.com.model.PhongBan;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
255
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageButton;
import android.widget.ListView;
/**
* Class dng x l chuyn phng ban cho nhn vin
* @author drthanh
*
*/
public class ChuyenPhongBanActivity extends Activity {
ListView lvPb;
private static ArrayList<PhongBan>arrPhongBan=null;
ArrayAdapter<PhongBan>adapter;
ImageButton btnApply;
NhanVien nv=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chuyen_phong_ban);
getFormWidgets();
//ly nhn vin t mn hnh xem danh sch nhn vin
Intent i=getIntent();
Bundle b= i.getBundleExtra("DATA");
nv=(NhanVien) b.getSerializable("NHANVIEN");
}
/**
* hm ly control theo id
* ng thi load ton b danh sch phng ban MainActivity
* ln ListView s dng
* android.R.layout.simple_list_item_single_choice ->dng Radio
* Bt buc phi x l hm: lvPb.setOnItemClickListener
* gn checked cho Radio
*/
public void getFormWidgets()
{
lvPb=(ListView) findViewById(R.id.lvphongban);
btnApply=(ImageButton) findViewById(R.id.imgapply);
arrPhongBan=MainActivity.getListPhongBan();
adapter=new ArrayAdapter<PhongBan>
(this, android.R.layout.simple_list_item_single_choice,
arrPhongBan);
lvPb.setAdapter(adapter);
lvPb.setOnItemClickListener(new OnItemClickListener() {
boolean somethingChecked = false;
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int
arg2,
long arg3) {
//hin nhin View arg1 l CheckedTextView
if(somethingChecked){
CheckedTextView cv = (CheckedTextView) arg1;
256
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
cv.setChecked(false);
}
CheckedTextView cv = (CheckedTextView) arg1;
if(!cv.isChecked())
{
cv.setChecked(true);
arrPhongBan.get(arg2).themNv(nv);
}
somethingChecked=true;
}
});
//khi chn nt Apply th tin hnh ng mn hnh ny
//v truyn lnh v cho DanhSachNhanVienACtivity
btnApply.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
doApply();
}
});
}
public void doApply()
{
setResult(MainActivity.CHUYENPHONG_THANHCONG);
finish();
}
}
- Ta qua mn hnh cui cng: Thit lp trng ph phng cho nhn vin
- Mn hnh ny l mn hnh con ca MainActivity.
- Khi chn phng ban no th thit lp trng ph phng cho phng ban .
- xem Layout (activity_thiet_lap_truong_phong.xml):
257
</pre>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ThietLapTruongPhongActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:text="Chn trng phng"
android:textColor="#FFFFFF"
android:textSize="15sp" />
<ListView
android:id="@+id/lvtruongphong"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3" >
</ListView>
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:text="Chn ph phng"
258
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
android:textColor="#FFFFFF"
android:textSize="15sp" />
<ListView
android:id="@+id/lvphophong"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2" >
</ListView>
<ImageButton
android:id="@+id/imgapply"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_gravity="center"
android:contentDescription="Thit lp"
android:src="@drawable/apply" />
</LinearLayout>
<pre>
- xem x l coding:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package tranduythanh.com.activity;
import java.util.ArrayList;
import tranduythanh.com.activity.R;
import tranduythanh.com.model.ChucVu;
import tranduythanh.com.model.NhanVien;
import tranduythanh.com.model.PhongBan;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.app.Activity;
import android.content.Intent;
/**
* mn hnh s hin th danh sch nhn vin vo 2 ListView
khc nhau
* ListView 1 dng Radio chn trng phng
* ListView 2 dng Checkbox chn ph phng
* @author drthanh
*
*/
public class ThietLapTruongPhongActivity extends Activity {
ListView lvtruongphong,lvphophong;
ArrayList<NhanVien>arrNvForTP=new ArrayList<NhanVien>();
259
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
ArrayAdapter<NhanVien> adapterForTP;
ArrayList<NhanVien>arrNvForPP=new ArrayList<NhanVien>();
ArrayAdapter<NhanVien> adapterForPP;
ImageButton btnApply;
int lastChecked=-1;
PhongBan pb=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thiet_lap_truong_phong);
getFormWidgets();
}
/**
* hm ly control theo id
* x l s kin checked (chn chc v cho nhn vin)
* Mi th l hng i tng nn n t tham chiu
*/
public void getFormWidgets()
{
lvtruongphong=(ListView) findViewById(R.id.lvtruongphong);
lvtruongphong.setTextFilterEnabled(true);
lvtruongphong.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lvtruongphong.setOnItemClickListener(new
OnItemClickListener() {
boolean somethingChecked = false;
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int
arg2,
long arg3) {
arrNvForTP.get(arg2).setChucvu(ChucVu.TruongPhong);
if(somethingChecked){
CheckedTextView cv = (CheckedTextView) arg1;
cv.setChecked(false);
}
CheckedTextView cv = (CheckedTextView) arg1;
if(!cv.isChecked())
{
cv.setChecked(true);
arrNvForTP.get(arg2).setChucvu(ChucVu.TruongPhong);
}
else
{
arrNvForTP.get(arg2).setChucvu(ChucVu.NhanVien);
}
lastChecked = arg2;
somethingChecked=true;
}
});
lvphophong=(ListView) findViewById(R.id.lvphophong);
lvphophong.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int
arg2,
260
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
long arg3) {
CheckedTextView cv = (CheckedTextView) arg1;
if(!cv.isChecked())
{cv.setChecked(true);
arrNvForPP.get(arg2).setChucvu(ChucVu.PhoPhong);
}
else
{cv.setChecked(false);
arrNvForPP.get(arg2).setChucvu(ChucVu.NhanVien);
}
}
});
adapterForTP=new ArrayAdapter<NhanVien>(this,
android.R.layout.simple_list_item_single_choice,
arrNvForTP);
adapterForPP=new ArrayAdapter<NhanVien>(this,
android.R.layout.simple_list_item_multiple_choice,
arrNvForPP);
lvtruongphong.setAdapter(adapterForTP);
lvphophong.setAdapter(adapterForPP);
//Ly c phng ban gi qua t MainActivity
Intent i= getIntent();
Bundle bundle= i.getBundleExtra("DATA");
pb= (PhongBan) bundle.getSerializable("PHONGBAN");
addNvToListTP(pb);
addNvToListPP(pb);
adapterForTP.notifyDataSetChanged();
adapterForPP.notifyDataSetChanged();
btnApply=(ImageButton) findViewById(R.id.imgapply);
btnApply.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
doApply();
}
});
}
/**
* gi thng tin li Mainactivity sau khi thit lp
*/
public void doApply()
{
Intent i=getIntent();
Bundle bundle=new Bundle();
bundle.putSerializable("PHONGBAN", pb);
i.putExtra("DATA", bundle);
setResult(MainActivity.THIET_LAP_TP_PP_THANHCONG, i);
finish();
}
/**
* duyt ton b nhn vin vo danh sch ng vin Trng phng
261
* @param pb
*/
public void addNvToListTP(PhongBan pb)
{
arrNvForTP.clear();
for(NhanVien nv:pb.getListNhanVien())
{
arrNvForTP.add(nv);
}
}
/**
* duyt ton b nhn vin vo danh sch ng vin ph phng
* @param pb
*/
public void addNvToListPP(PhongBan pb)
{
arrNvForPP.clear();
for(NhanVien nv:pb.getListNhanVien())
{
arrNvForPP.add(nv);
}
}
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
}
262
263
264
265
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2"
android:background="#008000"
android:gravity="center"
android:text=""Chi Chi" Phone Utility"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
266
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name:" />
<EditText
android:id="@+id/editName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone:" />
<EditText
android:id="@+id/editPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="phone" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnSaveContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="Save Contact" />
</TableRow>
</TableLayout>
<TextView
267
86
87
88
89
90
91
92
93
94
95
96
97
android:id="@+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000" />
<ListView
android:id="@+id/lvContact"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
package tranduythanh.com;
import java.io.Serializable;
public class MyContact implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public MyContact(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public MyContact() {
super();
}
@Override
public String toString() {
return this.name+"["+this.phone+"]";
}
}
268
- Class x l MainActivity:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package tranduythanh.com;
import java.util.ArrayList;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
EditText editName,editPhone;
Button btnSave;
ListView lvContact;
//Danh sch contact a vo ListView
ArrayList<MyContact>arrContact=new ArrayList<MyContact>();
ArrayAdapter<MyContact>adapter=null;
MyContact selectedContact=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doGetFormWidgets();
doAddEvents();
}
public void doGetFormWidgets()
{
btnSave=(Button) findViewById(R.id.btnSaveContact);
editName=(EditText) findViewById(R.id.editName);
editPhone=(EditText) findViewById(R.id.editPhone);
lvContact=(ListView) findViewById(R.id.lvContact);
//to i tng adapter
adapter=new ArrayAdapter<MyContact>
(this, android.R.layout.simple_list_item_1,arrContact);
//gn Adapter vo cho ListView
lvContact.setAdapter(adapter);
//thit lp contextmenu cho ListView
registerForContextMenu(lvContact);
}
public void doAddEvents()
{
btnSave.setOnClickListener(new OnClickListener() {
269
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
doSaveContact();
}
});
//ly contact c chn trc trong ListView
//V khi m context menu s lm mt focus nn ta phi lu
li trc
//khi m context menu
lvContact.setOnItemLongClickListener(new
OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View
arg1,
int arg2, long arg3) {
//lu vt contact c chn trong ListView
selectedContact=arrContact.get(arg2);
return false;
}
});
}
/**
* mi ln nhn Save contact th gi hm ny
* cp nht contact vo List view
* bn lu l ta ch lm trong b nh
* khng phi lu vo Danh B (phn ny hc sau)
*/
public void doSaveContact()
{
MyContact ct=new MyContact();
ct.setName(editName.getText()+"");
ct.setPhone(editPhone.getText()+"");
arrContact.add(ct);
adapter.notifyDataSetChanged();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
//gn context menu vo
getMenuInflater().inflate(R.menu.phonecontextmenu, menu);
menu.setHeaderTitle("Call- Sms");
menu.getItem(0).setTitle("Call to
"+selectedContact.getPhone());
menu.getItem(1).setTitle("Send sms to
"+selectedContact.getPhone());
}
@Override
public boolean onContextItemSelected(MenuItem item) {
//kim tra xem Menu Item no c chn
switch(item.getItemId())
270
{
case R.id.mnuCall:
doMakeCall();
break;
case R.id.mnuSms:
doMakeSms();
break;
case R.id.mnuRemove:
arrContact.remove(selectedContact);
adapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
/**
* Thc hin gi in thoi
*/
public void doMakeCall()
{
Uri uri=Uri.parse("tel:"+selectedContact.getPhone());
Intent i=new Intent(Intent.ACTION_CALL, uri);
startActivity(i);
}
/**
* thc hin m giao din gi tin nhn
* Truyn thng tin contact ang chn qua
* activity mi
*/
public void doMakeSms()
{
Intent i=new Intent(this, MySMSActivity.class);
Bundle b=new Bundle();
b.putSerializable("CONTACT", selectedContact);
i.putExtra("DATA", b);
startActivity(i);
}
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
}
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
271
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MySMSActivity extends Activity {
Button btnSendSMS;
EditText editContent;
TextView txtSendTo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_sms);
btnSendSMS =(Button) findViewById(R.id.btnSendSms);
editContent =(EditText) findViewById(R.id.editSMS);
txtSendTo=(TextView) findViewById(R.id.txtSendTo);
//Ly thng tin t Intent
Intent i =getIntent();
Bundle b=i.getBundleExtra("DATA");
final MyContact c=(MyContact) b.getSerializable("CONTACT");
btnSendSMS.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
sendSms(c);
}
});
txtSendTo.setText("Send to : "+c.getPhone());
}
/**
* hm dng gi tin nhn c kim tra kt qu tr v
* Ti cha gii thch y c v n lin quan rt nhiu
* kin thc, khi no ti Broadcast Receiver, telephony Ti s
* gii thch li
* @param c
*/
public void sendSms(MyContact c)
{
//ly mc nh SmsManager
final SmsManager sms = SmsManager.getDefault();
Intent msgSent = new Intent("ACTION_MSG_SENT");
//Khai bo pendingintent kim tra kt qu
final PendingIntent pendingMsgSent =
PendingIntent.getBroadcast(this, 0, msgSent, 0);
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
int result = getResultCode();
272
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
273
- Ting Php:
- Ting vit:
276
-Bn xem 3 tp tin strings.xml 3 ngn ng khc nhau (nh l phi cng id):
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#80FFFF" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
- Xem coding:
1
2
3
4
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
277
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv=(ListView) findViewById(R.id.listView1);
ArrayAdapter<String>adapter=new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.myarray));
lv.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
278
279
- Khi nhn chn Read Data, chng trnh s c ni dung t myfile.txt v hin th ln EditText.
- y Ti mun hi cc bn l : Ti sao cc resource c ng gi trong APK li l Read
Only?. Ti ngh cu tr li n gin nht l s dng ti u b nh. V in thoi khng ging
nh my tnh, b nh trong ca n khng c bao la bt ngt nh PC, mi phn mm (.APK) c ci
t vo th n s khng mun Co Gin dung lng v n cn qun l phn mm ti u nht (s
dng b nh t nht).
- Bn xem cu trc XML ca giao din (activity_main.xml):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/btnreaddata"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Read Data" />
<EditText
android:id="@+id/editdata"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="2"
android:ems="10"
android:gravity="top|left"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
13
14
15
16
17
18
19
20
21
22
23
24
while((data=bufreader.readLine())!=null)
{
builder.append(data);
builder.append("\n");
}
in.close();
editdata.setText(builder.toString());
}
catch(IOException ex){
Log.e("ERROR", ex.getMessage());
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/btnreaddata"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Read Data" />
<EditText
android:id="@+id/editdata"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="2"
android:ems="10"
android:gravity="top|left"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btnwritedata"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Write Data" />
</LinearLayout>
- Source Activity
282
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package tranduythanh.com;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements
OnClickListener{
Button btnread,btnwrite;
EditText editdata;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnread=(Button) findViewById(R.id.btnreaddata);
btnwrite=(Button) findViewById(R.id.btnwritedata);
editdata=(EditText) findViewById(R.id.editdata);
btnread.setOnClickListener(this);
btnwrite.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId()==R.id.btnreaddata)
{
readData();
}
else if(v.getId()==R.id.btnwritedata)
{
writeData();
}
}
/**
* Hm c tp tin trong Android
* Dng openFileInput trong Android c
* ra FileInputStream
*/
public void readData()
{
try {
FileInputStream in= openFileInput("myfile.txt");
BufferedReader reader=new
BufferedReader(new InputStreamReader(in));
283
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
String data="";
StringBuilder builder=new StringBuilder();
while((data=reader.readLine())!=null)
{
builder.append(data);
builder.append("\n");
}
in.close();
editdata.setText(builder.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Hm ghi tp tin trong Android
* dng openFileOutput ghi
* openFileOutput to ra FileOutputStream
*/
public void writeData()
{
try {
FileOutputStream out=
openFileOutput("myfile.txt",0);
OutputStreamWriter writer=
new OutputStreamWriter(out);
writer.write(editdata.getText().toString());
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* hm ny l c Resource File, Ti gom chung vo y
*/
public void readData2()
{
String data;
InputStream in= getResources()
.openRawResource(R.drawable.myfile);
InputStreamReader inreader=new InputStreamReader(in);
BufferedReader bufreader=new BufferedReader(inreader);
StringBuilder builder=new StringBuilder();
if(in!=null)
{
try{
while((data=bufreader.readLine())!=null)
{
builder.append(data);
builder.append("\n");
}
in.close();
284
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
editdata.setText(builder.toString());
}
catch(IOException ex){
Log.e("ERROR", ex.getMessage());
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
- hnh trn bn vo DDMS, ti th mc mnt/ chn sdcard. Phi chn cho ng v n c nhiu th
mc cng tn sdcard, nhng bn chn sdcard trong th mc mnt thi. Sau ko th tp tin vo
y l xong.
- XML Resource y x nh phn internal Storage nn Ti khng a vo y, bn xem Source code
Activity:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package tranduythanh.com;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements
OnClickListener{
Button btnread,btnwrite;
EditText editdata;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
286
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
setContentView(R.layout.activity_main);
btnread=(Button) findViewById(R.id.btnreaddata);
btnwrite=(Button) findViewById(R.id.btnwritedata);
editdata=(EditText) findViewById(R.id.editdata);
btnread.setOnClickListener(this);
btnwrite.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId()==R.id.btnreaddata)
{
readData();
}
else if(v.getId()==R.id.btnwritedata)
{
writeData();
}
}
/*
* c t SD Card
*
Environment.getExternalStorageDirectory().getAbsolutePath()
* ly ng dn trn SD Card
*/
public void readData()
{
String sdcard=Environment
.getExternalStorageDirectory()
.getAbsolutePath()+"/myfile.txt";
try {
Scanner scan=new Scanner(new File(sdcard));
String data="";
while(scan.hasNext())
{
data+=scan.nextLine()+"\n";
}
scan.close();
editdata.setText(data+"");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* ghi tp tin trn SD Card
*/
public void writeData()
{
String sdcard=Environment
.getExternalStorageDirectory()
.getAbsolutePath()+"/myfile.txt";
try {
OutputStreamWriter writer=
new OutputStreamWriter(
new FileOutputStream(sdcard));
writer.write(editdata.getText()+"");
writer.close();
287
81
82
83
84
85
86
87
88
89
90
91
92
93
94
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
- Khi thc thi ng dng, bn s c giao din nh trnh by trn, vi kt qu nh mong mun.
288
- Bn c th ti coding mu y:
http://www.mediafire.com/download/1ydvjc8wvizzjcm/LearnFileExternalStorage.rar
3) Saving cache files:
- Li ch ca cache files l g? tng tc x l ca ng dng khi bn thng xuyn truy cp
internet th bn nn lu cache.
- Khi lu cache th n s u trong in thoi? bn xem hnh:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/btncreatecache"
289
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create Cache" />
<EditText
android:id="@+id/editdata"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="2"
android:ems="10"
android:gravity="top|left"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btnreadcache"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Read Cache" />
</LinearLayout>
- X l code Activity:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package tranduythanh.com;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements
OnClickListener{
Button btncreatecache,btnreadcache;
EditText editdata;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btncreatecache=(Button) findViewById(R.id.btncreatecache);
btnreadcache=(Button) findViewById(R.id.btnreadcache);
editdata =(EditText) findViewById(R.id.editdata);
290
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
btncreatecache.setOnClickListener(this);
btnreadcache.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.btncreatecache)
{
createCache();
}
else if(v.getId()==R.id.btnreadcache)
{
readCache();
}
}
/**
* Ly ton b file cache
*/
public void loadAllCache()
{
File pathCacheDir = getCacheDir();
File []listCache= pathCacheDir.listFiles();
for(File f :listCache)
{
//process f here
f.delete();
}
}
/**
* c cache file
* getCacheDir() tr v ng th mc cache
*/
public void readCache() {
try {
File pathCacheDir = getCacheDir();
String strCacheFileName = "myCacheFile.cache";
File newCacheFile = new
File(pathCacheDir, strCacheFileName);
Scanner sc=new Scanner(newCacheFile);
String data="";
while(sc.hasNext())
{
data+=sc.nextLine()+"\n";
}
editdata.setText(data);
sc.close();
291
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* Lu cache file
*/
public void createCache()
{
try {
File pathCacheDir = getCacheDir();
String strCacheFileName = "myCacheFile.cache";
String strFileContents = editdata.getText()+"";
File newCacheFile = new
File(pathCacheDir, strCacheFileName);
newCacheFile.createNewFile();
FileOutputStream foCache =
new FileOutputStream(
newCacheFile.getAbsolutePath());
foCache.write(strFileContents.getBytes());
foCache.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- V giao din v cch chy tng t nh v d trc nn Ti khng chp hnh minh ha,
- Bn c th ti coding mu
y: http://www.mediafire.com/download/u0smn6v68xf6uc5/LearnCacheFile.rar
- Nh vy ti gii thiu xong tng tc tp tin trong Android: internal Storage, external storage,
caching file
- Trong bi tp k tip Ti s hng dn cc bn cch tng tc vi XML file trong Android, trong
bi tp ny Ti mun trnh by v 2 k thut duyt tp tin XML l : DOM v SAX. Ti thy n
rt hay, cc bn nn ch theo di.
292
293
Bc 1:
c th s dng c k thut DOM trong Android, chng ta import cc th vin sau (k c nhng
th vin bt li):
1
2
3
4
5
6
7
8
9
10
11
12
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
DocumentBuilderFactory
fac=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=fac.newDocumentBuilder();
Bc 3:
To FileInputStream t tp tin XML ngun ( y Ti XML ngun trong SD Card):
1
2
3
String
sdcard=Environment.getExternalStorageDirectory().getAbsolutePath();
String xmlfile=sdcard+"/employee.xml";
FileInputStream fIn=new FileInputStream(xmlfile);
Bc 4:
Dng phng thc parse ca i tng builder bc 2 to Document
1
Document doc=builder.parse(fIn);
Bc 5:
294
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- Bn c th ti code mu
y:http://www.mediafire.com/download/04q4rlg33nmrina/LearnXMLParser_DOM.rar (Ti c nh
km employee.xml trong project ny, bn ch vic ko th n vo SD Card trong my ca bn l ok).
.getAttributeValue()
- Bc 1:
- Ta cn import cc th vin sau:
1
2
3
4
5
6
7
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
XmlPullParserFactory fc=XmlPullParserFactory.newInstance();
XmlPullParser parser= fc.newPullParser();
296
- Bc 3:
- To FileInputStream t xml source (XML trong SD Card)
1
2
3
4
String sdcard=Environment.
getExternalStorageDirectory().getAbsolutePath();
String xmlfile=sdcard+"/employee.xml";
FileInputStream fIn=new FileInputStream(xmlfile);
- Bc 4:
- Tin hnh duyt
parser.setInput(fIn, "UTF-8");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
int eventType=-1;
String nodeName;
String datashow="";
while(eventType!=XmlPullParser.END_DOCUMENT)//cha kt thc
ti liu
{
eventType=parser.next();// bt u duyt
switch(eventType)
{
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.END_DOCUMENT:
break;
case XmlPullParser.START_TAG://l tag m
nodeName=parser.getName();
if(nodeName.equals("employee")){// kim tra ng tag mnh mun
hay khng
datashow+=parser.getAttributeValue(0)+"-";//ly gi tr ca
thuc tnh
datashow+=parser.getAttributeValue(1)+"-";
}
else if(nodeName.equals("name")){
datashow+=parser.nextText()+"-";//ly ni dung tag element
}
else if(nodeName.equals("phone")){
datashow+=parser.nextText()+"-";
}
break;
case XmlPullParser.END_TAG://l tag ng
nodeName=parser.getName();
if(nodeName.equals("employee")){
datashow+="\n----------------\n";
}
break;
}
}
//da vo datashow hin th ln giao din
297
- Bn c th ti code mu y
: http://www.mediafire.com/download/fh22pkib490n7lf/LearnXMLParser_SAX.rar
-Bi tp dnh cho c gi:
- Duyt XML bng DOM v SAX
- Title ca cc tag XML ta a vo Spinner (ch khng a trng lp)
- Cc thng tin khc a vo ListView
- Mi ln chn Title trong Spinner th ch hin th nhng employee theo Title ny trong XML m thi
298
******** Gi *******
300
- Chn nt Thot, chng trnh tip tc ng Activity ny gip tt hn cc Activity trong ng dng.
- Khi ng li chng trnh s phi t ng load li thng tin ng nhp trc (Nu khi ng
nhp c chn Lu thng tin).
- Bn xem cu trc ca Project:
301
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#80FFFF"
android:gravity="center"
android:text="ng nhp h thng" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
302
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User:" />
<EditText
android:id="@+id/editUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pasword:" />
<EditText
android:id="@+id/editPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<CheckBox
android:id="@+id/chksaveacount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="Lu thng tin" />
303
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
</TableRow>
<TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnlogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="ng nhp" />
</TableRow>
</TableLayout>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".DangNhapThanhCongActivity" >
<TextView
android:id="@+id/txtmsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="20sp" />
<Button
android:id="@+id/btnThoat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Thot" />
</LinearLayout>
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
304
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
public class MainActivity extends Activity {
Button btnlogin;
EditText edituser,editpassword;
CheckBox chksaveaccount;
//t tn cho tp tin lu trng thi
String prefname="my_data";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlogin=(Button) findViewById(R.id.btnlogin);
edituser =(EditText)
findViewById(R.id.editUser);
editpassword=(EditText)
findViewById(R.id.editPassword);
chksaveaccount=(CheckBox)
findViewById(R.id.chksaveacount);
btnlogin.setOnClickListener(
new View.OnClickListener() {
public void onClick(View arg0) {
doLogin();
}
});
}
/**
* hm ng nhp h thng
*/
public void doLogin()
{
finish();//ng mn hnh hin ti
Intent i=new Intent(this, DangNhapThanhCongActivity.class);
//truyn d liu qua mn hnh mi
i.putExtra("user", edituser.getText().toString());
startActivity(i);//m mn hnh mi
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//gi hm lu trng thi y
savingPreferences();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//gi hm c trng thi y
restoringPreferences();
}
/**
* hm lu trng thi
305
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
*/
public void savingPreferences()
{
//to i tng getSharedPreferences
SharedPreferences pre=getSharedPreferences
(prefname, MODE_PRIVATE);
//to i tng Editor lu thay i
SharedPreferences.Editor editor=pre.edit();
String user=edituser.getText().toString();
String pwd=editpassword.getText().toString();
boolean bchk=chksaveaccount.isChecked();
if(!bchk)
{
//xa mi lu tr trc
editor.clear();
}
else
{
//lu vo editor
editor.putString("user", user);
editor.putString("pwd", pwd);
editor.putBoolean("checked", bchk);
}
//chp nhn lu xung file
editor.commit();
}
/**
* hm c trng thi lu trc
*/
public void restoringPreferences()
{
SharedPreferences pre=getSharedPreferences
(prefname,MODE_PRIVATE);
//ly gi tr checked ra, nu khng thy th gi tr mc
nh l false
boolean bchk=pre.getBoolean("checked", false);
if(bchk)
{
//ly user, pwd, nu khng thy gi tr mc nh l rng
String user=pre.getString("user", "");
String pwd=pre.getString("pwd", "");
edituser.setText(user);
editpassword.setText(pwd);
}
chksaveaccount.setChecked(bchk);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
306
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class DangNhapThanhCongActivity extends Activity {
TextView txtMsg;
Button btnThoat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dang_nhap_thanh_cong);
txtMsg=(TextView) findViewById(R.id.txtmsg);
btnThoat=(Button) findViewById(R.id.btnThoat);
btnThoat.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent i=getIntent();
txtMsg.setText("Hello : "+i.getStringExtra("user"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.activity_dang_nhap_thanh_cong,
menu);
return true;
}
}
307
- t tn ty ( y Ti t tn mypreferencelayout)
- Khng ging nh layout bnh thng, preference screen s nm trong th mc xml nh hnh bn
di:
- Tin hnh to Checkbox ging nh trn. (n c nhiu control khc, ty vo nhu cu)
308
Bc 2:
- To Activity cho Prefence layout trn (K tha t PreferenceActivity):
Bc 3:
- Cu hnh Manifest XML cho Preference Activity trn:
Bc 4:
- Tin hnh sa MainActivity s dng Preference Activity (ng
kOnSharePreferenceChangeListener):
- Bn c th xem kt qu nh bn di:
309
V d 2:
- Bn c gng t xem li l thuyt v c coding hiu. V d ny Ti khng gii thch coding.
- Hay bn cn to ra cc mn hnh cu hnh (ging nh mn hnh Setting ca thit b chng hn
cn bit Shared Preference Change Listeners):
310
- Bn ti source code
y: http://www.mediafire.com/download/lg8881lz8jrp1np/Ex_Module3_Bai5.rar
311
Kiu d liu
M t
malop
TEXT
Kha chnh
tenlop
TEXT
siso
INTEGER
tblsinhvien
Tn ct
Kiu d liu
M t
masv
TEXT
Kha chnh
tensv
TEXT
malop
TEXT
kha ngoi
313
314
- V bng sinh vin c cha kha ngoi tham chiu ti bng lp, nn bn phi ch dng lnh
tham chiu trn.
3) Cch thm/ sa/ xa d liu trong bng:
- Cch thm mt dng d liu vo trong bng:
+ Dng i tng ContentValues a d liu vo bng. i tng ny c cc phng
thc put(tn ct , d liu)
+ Sau gi phng thc insert a i tng (dng ny) vo bng.
+ Bn ch l phng thc insert c rt nhiu loi i s khc nhau, nhng y Ti ch ni 1 loi
n gin nht (cc kiu khc bn t tm hiu thm). Loi m Ti mun cp ti l khng lin
quan g ti kim tra cc iu kin, ch cn a i tng ContentValues vo insert l bn s c
c 1 dng mi:
315
- Nhn vo on code trn, bn thy Ti s dng c 3 ct malop, tenlop, siso ca bng lp hc:
values.put(malop,DHTH7C) ; tc l a gi tr DHTH7C vo ct malop.
- dng lnh database.insert(tbllop,null,values); i s 1 l tn bng, i s 2 bn truyn null, i
s 3 bn truyn i tng values
- Nu thm thnh cng th s tr v gi tr khc -1. Nu bng -1 l tht bi.
- Cch cp nht d liu:
- Ta dng hm update cp nht d liu theo mt iu kin bt k no .
public int update
(String table, ContentValues values,
- i s 1 l tn bng
- i s 2 l i tng mun chnh sa (vi gi tr mi)
- i s 3 l tp cc iu kin lc (dng du chm hi ? to iu kin lc)
- i s 4 l tp cc gi tr ca iu kin lc (ly theo ng th t)
- Hm ny tr v s dng b nh hng. V d nu c 3 dng b thay i th n tr v 3. nu khng c
dng no b nh hng th n tr v 0.
V d: Ti vit hm chnh sa (bn cng nn tch thnh tng hm ging vy):
316
String whereClause,
String[] whereArgs)
- i s 1 l tn bng
- i s 2 l tp iu kin lc (dng ? to)
- i s 3 l tp cc gi tr ca iu kin lc
- Hm tr v s dng b nh hng.
- Mun xa ton b d liu trong bng th ta truyn null vo 2 i s cui:
- Mun xa theo 1 m no :
columns
A list of which columns to return. Passing null will return all columns,
which is discouraged to prevent reading data from storage that isnt
going to be used.
selection
selectionArgs
groupBy
having
orderBy
318
319
Khi chn chc nng thm Tc gi, chng trnh s xut hin mn hnh di y (ch m
di dng Dialog):
Khi chn xem danh sch Tc gi, chng trnh s m mt mn hnh mi hin th danh
sch Tc gi to ch dng CustomLayout cho ListView:
320
Khi chn tng tc gi trong danh sch, s hin th mn hnh cho php chnh sa tc gi:
Khi nhn Tht Lu (Long time) vo tng tc gi trong danh sch, chng trnh s hin th
Alert Dialog hi xem c mun xa Tc gi ny hay khng?
321
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#004000"
android:gravity="center"
android:text="Qun L Sch"
android:textColor="#FFFFFF"
android:textSize="20sp" />
322
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<Button
android:id="@+id/btnInsertAuthor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Thm Tc Gi" />
<Button
android:id="@+id/buttonShowAuthorList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Xem danh sch Tc Gi" />
<Button
android:id="@+id/buttonInsertBook"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:text="Qun l Sch" />
</LinearLayout>
package tranduythanh.com;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
* hm hnh chnh cho php chn cc thao tc
* @author drthanh
*
*/
public class MainActivity extends Activity {
Button btnCreateDatabase=null;
Button btnInsertAuthor=null;
Button btnShowAuthorList=null;
Button btnShowAuthorList2=null;
Button btnTransaction=null;
Button btnShowDetail=null;
Button btnInsertBook=null;
public static final int OPEN_AUTHOR_DIALOG=1;
323
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
ShowListAuthorActivity.class);
startActivity(intent);
}
/**
* hm xem danh sch tc gi dng ListActivity
* Ti lm 2 cch cc bn n tp li ListView
* bn gi hm no th gi 1 thi showAuthorList1 hoc
showAuthorList2
*/
public void showAuthorList2()
{
Intent intent=new Intent(MainActivity.this,
ShowListAuthorActivity2.class);
startActivity(intent);
}
/**
* Ti cung cp thm hm ny cc bn nghin cu thm v
transaction
*/
public void interactDBWithTransaction()
{
if(database!=null)
{
database.beginTransaction();
try
{
//lm ci g tm lum y,
//ch cn c li sy ra th s kt thc transaction
ContentValues values=new ContentValues();
values.put("firstname", "xx");
values.put("lastname", "yyy");
database.insert("tblAuthors", null, values);
database.delete("tblAuthors", "ma=?", new String[]{"x"});
//Khi no hm ny c gi th cc thao tc bn trn mi thc
hin c
//Nu n khng c gi th mi thao tc bn trn u b hy
database.setTransactionSuccessful();
}
catch(Exception ex)
{
Toast.makeText(MainActivity.this, ex.getMessage(),
Toast.LENGTH_LONG).show();
}
finally
{
database.endTransaction();
}
}
}
/**
* hm x l kt qu tr v
*/
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
326
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_simple_database_main,
menu);
return true;
}
}
- XML source thm tc gi activity_create_author.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M tc gi:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editTextFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
328
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
android:text="Tn tc gi:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editTextLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/buttonClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Xa trng" />
<Button
android:id="@+id/buttonInsert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lu tc gi" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
</TableLayout>
</LinearLayout>
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
/**
* class nhp thng tin tc gi
* Mi thay i u gi thng tin v MainActivity x l
* @author drthanh
*
329
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
*/
public class CreateAuthorActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_author);
final Button btnInsert =(Button)
findViewById(R.id.buttonInsert);
final EditText txtFirstname=(EditText)
findViewById(R.id.editTextFirstName);
final EditText txtLastname=(EditText)
findViewById(R.id.editTextLastName);
final Intent intent= getIntent();
btnInsert.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent();
Bundle bundle=new Bundle();
bundle.putString("firstname",
txtFirstname.getText().toString());
bundle.putString("lastname",
txtLastname.getText().toString());
intent.putExtra("DATA_AUTHOR", bundle);
setResult(MainActivity.SEND_DATA_FROM_AUTHOR_ACTIVITY,
intent);
CreateAuthorActivity.this.finish();
}
});
final Button btnClear=(Button) findViewById(R.id.buttonClear);
btnClear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
txtFirstname.setText("");
txtLastname.setText("");
txtFirstname.requestFocus();
}
});
Bundle bundle= intent.getBundleExtra("DATA");
if(bundle!=null && bundle.getInt("KEY")==1)
{
String f2=bundle.getString("getField2");
String f3=bundle.getString("getField3");
txtFirstname.setText(f2);
txtLastname.setText(f3);
btnInsert.setText("Update");
this.setTitle("View Detail");
/*TableRow row=(TableRow) findViewById(R.id.tableRow3);
row.removeViewAt(0);
row.setGravity(Gravity.RIGHT);*/
330
70
71
72
73
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_create_author,
menu);
return true;
}
}
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/TableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tc gi:" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2" />
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tn sch:" />
<EditText
android:id="@+id/editTextTitle"
331
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ngy XB:" />
<EditText
android:id="@+id/editTextDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="date" />
<Button
android:id="@+id/buttonDate"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="..." />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/buttonInsertBook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="3"
android:text="Thm Sch" />
</TableRow>
<TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
332
96
97
98
99
100
101
102
103
104
</TableRow>
<ListView
android:id="@+id/listViewBook"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</TableLayout>
package tranduythanh.com;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
/**
* class hin th thng tin Tc gi v Spinner
* v hin th thng tin sch vo ListView
* ng thi cho php thao tc vi sch
* Class ny l kh hiu nht, nhng ch l tng hp ca
* cc kin thc hc trc
* @author drthanh
*
*/
public class InsertBookActivity extends Activity {
SQLiteDatabase database=null;
List<InforData>listBook=null;
List<InforData>listAuthor=null;
InforData authorData=null;
MySimpleArrayAdapter adapter=null;
int day,month,year;
@Override
333
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
loadListBookByAuthor(authorData.getField1().toString());
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
authorData=null;
}
});
setCurrentDateOnView();
//lnh x l DatePickerDialog
Button bChangeDate=(Button) findViewById(R.id.buttonDate);
bChangeDate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(113);
}
});
//Lnh x l thm mi mt sn phm theo tc gi ang chn
Button btnInsertBook =(Button)
findViewById(R.id.buttonInsertBook);
btnInsertBook.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(authorData==null)
{
Toast.makeText(InsertBookActivity.this, "Please choose an
author to insert", Toast.LENGTH_LONG).show();
return;
}
EditText txtTitle=(EditText)
findViewById(R.id.editTextTitle);
ContentValues values=new ContentValues();
values.put("title", txtTitle.getText().toString());
Calendar c=Calendar.getInstance();
c.set(year, month, day);
SimpleDateFormat dfmt=new SimpleDateFormat("dd-MM-yyyy");
values.put("dateadded",dfmt.format(c.getTime()));
values.put("authorid", authorData.getField1().toString());
long bId=database.insert("tblBooks", null, values);
if(bId>0)
{
Toast.makeText(InsertBookActivity.this, "Insert Book OK",
Toast.LENGTH_LONG).show();
loadListBookByAuthor(authorData.getField1().toString());
}
else
{
Toast.makeText(InsertBookActivity.this, "Insert Book
Failed", Toast.LENGTH_LONG).show();
335
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
}
}
});
}
/*
* Hm hin th mi sch trong CSDL
*/
public void loadAllListBook()
{
Cursor cur=database.query("tblBooks", null, null, null,
null, null, null);
cur.moveToFirst();
listBook=new ArrayList<InforData>();
while(cur.isAfterLast()==false)
{
InforData d=new InforData();
d.setField1(cur.getInt(0));
d.setField2(cur.getString(1));
d.setField3(cur.getString(2));
listBook.add(d);
cur.moveToNext();
}
cur.close();
adapter=new MySimpleArrayAdapter(InsertBookActivity.this,
R.layout.my_layout_for_show_list_data, listBook);
ListView lv=(ListView) findViewById(R.id.listViewBook);
lv.setAdapter(adapter);
}
/**
* hm hin th sch theo tc gi
* @param authorid
*/
public void loadListBookByAuthor(String authorid)
{
Cursor cur=database.query("tblBooks", null, "authorid=?",
new String[]{authorid}, null, null, null);
cur.moveToFirst();
listBook=new ArrayList<InforData>();
while(cur.isAfterLast()==false)
{
InforData d=new InforData();
d.setField1(cur.getInt(0));
d.setField2(cur.getString(1));
d.setField3(cur.getString(2));
listBook.add(d);
cur.moveToNext();
}
cur.close();
adapter=new MySimpleArrayAdapter(InsertBookActivity.this,
R.layout.my_layout_for_show_list_data, listBook);
ListView lv=(ListView) findViewById(R.id.listViewBook);
lv.setAdapter(adapter);
}
@Override
protected Dialog onCreateDialog(int id) {
336
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:gravity="left"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_weight="0.4"
android:gravity="left"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_weight="0.4"
android:text="Medium Text"
android:gravity="left"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
package tranduythanh.com;
/**
* class dng chung c d liu hin th ln ListView Sch
v tc gi
* bn c th b class ny vit class khc
* y Ti hi lm bing 1 cht l Ti mun vit 1 Class c
cc kiu Object
* n t hiu mi kiu d liu phi vit li nn bn c
c v kh hiu
* Nhng thi ---> rng ln
* @author drthanh
*
*/
public class InforData {
private Object field1;
private Object field2;
private Object field3;
338
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
}
package tranduythanh.com;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* class dng custom layout
* dng chung cho hin th Sch v Tc gi
* @author drthanh
*
*/
public class MySimpleArrayAdapter extends
ArrayAdapter<InforData> {
private Activity context;
private int layout;
private List<InforData>list;
public MySimpleArrayAdapter(Context context, int
textViewResourceId,
339
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
List<InforData> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
this.context=(Activity) context;
this.layout=textViewResourceId;
this.list=objects;
}
@Override
public View getView(int position, View convertView, ViewGroup
parent) {
// TODO Auto-generated method stub
LayoutInflater flater=context.getLayoutInflater();
View row=flater.inflate(layout, parent,false);
TextView txt1=(TextView) row.findViewById(R.id.textView1);
TextView txt2=(TextView) row.findViewById(R.id.textView2);
TextView txt3=(TextView) row.findViewById(R.id.textView3);
/*txt1.setTextAlignment(Gravity.LEFT);
txt2.setTextAlignment(Gravity.LEFT);
txt3.setTextAlignment(Gravity.LEFT);*/
InforData data=list.get(position);
txt1.setText(data.getField1()==null?"":data.getField1().toStri
ng());
txt2.setText(data.getField2()==null?"":data.getField2().toStri
ng());
txt3.setText(data.getField3()==null?"":data.getField3().toStri
ng());
if(position==0)
{
row.setBackgroundColor(Color.RED);
}
return row;
}
}
19
20
21
22
23
24
<Button
android:id="@+id/buttonBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
</LinearLayout>
package tranduythanh.com;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
/**
* class xem danh sch tc gi
* @author drthanh
*
*/
public class ShowListAuthorActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_show_data);
updateUI();
Button btn=(Button) findViewById(R.id.buttonBack);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ShowListAuthorActivity.this.finish();
}
});
}
List<InforData>list=new ArrayList<InforData>();
341
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
InforData dataClick=null;
SQLiteDatabase database=null;
MySimpleArrayAdapter adapter=null;
public void updateUI()
{
database=openOrCreateDatabase("mydata.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
if(database!=null)
{
Cursor cursor=database.query("tblAuthors", null, null, null,
null, null, null);
startManagingCursor(cursor);
InforData header=new InforData();
header.setField1("STT");
header.setField2("M tc gi");
header.setField3("Tn tc gi");
list.add(header);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
InforData data=new InforData();
data.setField1(cursor.getInt(0));
data.setField2(cursor.getString(1));
data.setField3(cursor.getString(2));
list.add(data);
cursor.moveToNext();
}
cursor.close();
adapter=new
MySimpleArrayAdapter(ShowListAuthorActivity.this,
R.layout.my_layout_for_show_list_data, list);
final ListView lv= (ListView)
findViewById(R.id.listViewShowData);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(ShowListAuthorActivity.this,"View -->"+
list.get(arg2).toString(), Toast.LENGTH_LONG).show();
Intent intent=new Intent(ShowListAuthorActivity.this,
CreateAuthorActivity.class);
Bundle bundle=new Bundle();
bundle.putInt("KEY", 1);
bundle.putString("getField1",
list.get(arg2).getField1().toString());
bundle.putString("getField2",
list.get(arg2).getField2().toString());
bundle.putString("getField3",
list.get(arg2).getField3().toString());
intent.putExtra("DATA", bundle);
dataClick=list.get(arg2);
startActivityForResult(intent,
342
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
MainActivity.OPEN_AUTHOR_DIALOG);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener()
{
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View
arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
final InforData data=list.get(arg2);
final int pos=arg2;
Toast.makeText(ShowListAuthorActivity.this, "Edit->"+data.toString(), Toast.LENGTH_LONG).show();
AlertDialog.Builder b=new
Builder(ShowListAuthorActivity.this);
b.setTitle("Remove");
b.setMessage("Xa ["+data.getField2() +" "+data.getField3() +"] h?");
b.setPositiveButton("C", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
int n=database.delete("tblAuthors", "id=?", new
String[]{data.getField1().toString()});
if(n>0)
{
Toast.makeText(ShowListAuthorActivity.this, "Remove ok",
Toast.LENGTH_LONG).show();
list.remove(pos);
adapter.notifyDataSetChanged();
}
else
{
Toast.makeText(ShowListAuthorActivity.this, "Remove not ok",
Toast.LENGTH_LONG).show();
}
}
});
b.setNegativeButton("Khng", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
b.show();
return false;
}
});
}
343
153
154
155
156
157
158
159
160
161
162
}
@Override
protected void onActivityResult(int requestCode, int
resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==MainActivity.SEND_DATA_FROM_AUTHOR_ACTIVITY)
{
Bundle bundle=data.getBundleExtra("DATA_AUTHOR");
String f2=bundle.getString("firstname");
String f3=bundle.getString("lastname");
String f1=dataClick.getField1().toString();
ContentValues values=new ContentValues();
values.put("firstname", f2);
values.put("lastname", f3);
if(database!=null)
{
int n=database.update("tblAuthors", values, "id=?", new
String[]{f1});
if(n>0)
{
Toast.makeText(ShowListAuthorActivity.this, "update ok ok ok
", Toast.LENGTH_LONG).show();
dataClick.setField2(f2);
dataClick.setField3(f3);
if(adapter!=null)
adapter.notifyDataSetChanged();
}
}
}
}
}
- Bn c th ti source code y
y: http://www.mediafire.com/download/nf4ghdbr44igpa6/Ex_Module3_Bai6.rar
- Bi tp k tip Ti s hng dn cc bn cch s dng Content Provider c danh b trong in
thoi, cch c lch s cuc gi, cch c Media trong in thoi cng nh bookmark. Bn ch
theo di
344
Cursor c=loader.loadInBackground();
cch 2:
Cursor c = getContentResolver() .query(uri, null, null, null, null);
- Ta s lm c th tng chc nng trong v d trn
- Bn xem cu trc ca bi tp ny:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/btnshowallcontact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show All Contact" />
<Button
android:id="@+id/btnaccesscalllog"
android:layout_width="match_parent"
346
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
android:layout_height="wrap_content"
android:text="Access The Call Log" />
<Button
android:id="@+id/btnmediastore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Access Media Store" />
<Button
android:id="@+id/btnaccessbookmarks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Access Bookmarks" />
</LinearLayout>
package tranduythanh.com;
import android.os.Bundle;
import android.provider.Browser;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.app.Activity;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements
OnClickListener{
Button btnshowallcontact;
Button btnaccesscalllog;
Button btnaccessmediastore;
Button btnaccessbookmarks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnshowallcontact=(Button)
findViewById(R.id.btnshowallcontact);
btnshowallcontact.setOnClickListener(this);
btnaccesscalllog=(Button)
findViewById(R.id.btnaccesscalllog);
btnaccesscalllog.setOnClickListener(this);
347
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
btnaccessmediastore=(Button)
findViewById(R.id.btnmediastore);
btnaccessmediastore.setOnClickListener(this);
btnaccessbookmarks=(Button)
findViewById(R.id.btnaccessbookmarks);
btnaccessbookmarks.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
Intent intent=null;
if(v==btnshowallcontact)
{
intent=new Intent(this, ShowAllContactActivity.class);
startActivity(intent);
}
else if(v==btnaccesscalllog)
{
accessTheCallLog();
}
else if(v==btnaccessmediastore)
{
accessMediaStore();
}
else if(v==btnaccessbookmarks)
{
accessBookmarks();
}
}
/**
* hm ly danh sch lch s cuc gi
* vi thi gian nh hn 30 giy v sp xp theo ngy gi
*/
public void accessTheCallLog()
{
String [] projection=new String[]{
Calls.DATE,
Calls.NUMBER,
Calls.DURATION
};
Cursor c=getContentResolver().query(
CallLog.Calls.CONTENT_URI,
projection,
Calls.DURATION+"<?",new String[]{"30"},
Calls.DATE +" Asc");
c.moveToFirst();
String s="";
348
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
while(c.isAfterLast()==false){
for(int i=0;i<c.getColumnCount();i++){
s+=c.getString(i)+" - ";
}
s+="\n";
c.moveToNext();
}
c.close();
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
/**
* hm c danh sch cc Media trong SD CARD
*/
public void accessMediaStore()
{
String []projection={
MediaStore.MediaColumns.DISPLAY_NAME,
MediaStore.MediaColumns.DATE_ADDED,
MediaStore.MediaColumns.MIME_TYPE
};
CursorLoader loader=new CursorLoader
(this, Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
Cursor c=loader.loadInBackground();
c.moveToFirst();
String s="";
while(!c.isAfterLast()){
for(int i=0;i<c.getColumnCount();i++){
s+=c.getString(i)+" - ";
}
s+="\n";
c.moveToNext();
}
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
c.close();
}
/**
* hm c danh sch Bookmark trong trnh duyt
*/
public void accessBookmarks()
{
String []projection={
Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL,
};
Cursor c=getContentResolver()
.query(Browser.BOOKMARKS_URI, projection,
null, null, null);
c.moveToFirst();
String s="";
int titleIndex=c.getColumnIndex
(Browser.BookmarkColumns.TITLE);
int urlIndex=c.getColumnIndex
(Browser.BookmarkColumns.URL);
while(!c.isAfterLast())
349
{
s+=c.getString(titleIndex)+" - "+
c.getString(urlIndex);
c.moveToNext();
}
c.close();
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
144
145
146
147
148
}
- Source XML x l xem danh bn (activity_show_all_contact.xml):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ShowAllContactActivity" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<Button
android:id="@+id/btnback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
</LinearLayout>
package tranduythanh.com;
import java.util.ArrayList;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
350
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import android.widget.ListView;
public class ShowAllContactActivity extends Activity {
Button btnback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_all_contact);
btnback=(Button) findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
showAllContacts1();
}
/**
* hm danh ton b danh b
* dng CursorLoader
*/
public void showAllContacts1()
{
Uri uri=Uri.parse("content://contacts/people");
ArrayList<String> list=new ArrayList<String>();
CursorLoader loader=new
CursorLoader(this, uri, null, null, null, null);
Cursor c1=loader.loadInBackground();
c1.moveToFirst();
while(c1.isAfterLast()==false){
String s="";
String idColumnName=ContactsContract.Contacts._ID;
int idIndex=c1.getColumnIndex(idColumnName);
s=c1.getString(idIndex)+" - ";
String
nameColumnName=ContactsContract.Contacts.DISPLAY_NAME;
int nameIndex=c1.getColumnIndex(nameColumnName);
s+=c1.getString(nameIndex);
c1.moveToNext();
list.add(s);
}
c1.close();
ListView lv=(ListView) findViewById(R.id.listView1);
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
/**
* hm danh ton b danh b
* dng getContentResolver
*/
public void showAllContacts2()
{
351
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
Uri uri=Uri.parse("content://contacts/people");
ArrayList<String> list=new ArrayList<String>();
Cursor c1=getContentResolver()
.query(uri, null, null, null, null);
c1.moveToFirst();
while(c1.isAfterLast()==false)
{
String s="";
String idColumnName=ContactsContract.Contacts._ID;
int idIndex=c1.getColumnIndex(idColumnName);
s=c1.getString(idIndex)+" - ";
String
nameColumnName=ContactsContract.Contacts.DISPLAY_NAME;
int nameIndex=c1.getColumnIndex(nameColumnName);
s+=c1.getString(nameIndex);
c1.moveToNext();
list.add(s);
}
c1.close();
ListView lv=(ListView) findViewById(R.id.listView1);
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if
it is present.
getMenuInflater().inflate(R.menu.activity_show_all_contact,
menu);
return true;
}
}
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="com.android.browser.permission.READ_HISTORY_BOOKMA
RKS" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="tranduythanh.com.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="tranduythanh.com.ShowAllContactActivity"
android:label="@string/title_activity_show_all_contact" >
</activity>
</application>
</manifest>
- Dng 11, 12, 13, 14 l cp quyn cho ng dng c th truy sut cc chc nng mong mun.
- By gi bn thc hin ng dng v quan st, gi Ti chy ln v dng chc nng xem ton b danh
b:
- Tng
t nh vy bn th cc chc nng cn li trong ng dng.
- Bn c th ti coding mu y
y: http://www.mediafire.com/download/kaac7d36ocvr8ba/LearnContentProvider.rar
- Bi tp k tip cc bn s c hc v mt k thut hon ton mi trong Android v rt kh v rt
hu dng, l k thut x l a Tin Trnh trong Android. Cc bn phi ch theo di v n v
cng quan trng, n cng ging nh Intent l huyt mch trong cc ng dng ca Android.
353
354