Вы находитесь на странице: 1из 440

AIIEKCIIi rOJIOIIIAnOB

nr
n 6n

"

ANDROID


ANDROID

nr
n11 6n
r
"'

-
-
2011

681.3.068
32.973.26-018.1
61

. .
61

Google Android: n .
.: -, 2011.-448 .: . + CD-ROM
( )

ISBN 978-5-9775-0562-8

Googl e A ndroid.
Android. ,
ndrid- .
,

-,

, ,
, A ndro i d .

Android SDK. -
.

681.3.068
32.973.26-018.1

N2 02429 24.07.00. n 27 10.10.


701001/16 . . n. . 36,12.
n. 2000 . N2 546
"-'', 190005, -, ., 29.
-n n
.
n n n .

N2 77.99.60.953..5770.05.09 26.05.2009

n n
"n ""
199034, -, 9 , 12

ISBN 978-5-9775-0562-8

. ., 2010
, "-r", 2010

.............................................

................................. ............. .................... l


.

. 1
2
. 6

................................... .......................... .................. ......... ..

...................... ......................... ..................................... ...................

.. .......................................................................... ................... .

......................................................................................................................

1.

Android ...... ......... .......................... 7


.

1.1.
.
.
1.1.1. IPC
.
.
1.1.2.
1.1.3.
. .
1.2. .. .
. .
..
1.2.1. libc .. ..
..
1.2.2.
1.2.3.
1.3.

...

7
8
9
.
. 9
.
. . 1
.
. 1
1
11
12

................ ............................ .... ..................... .................. . . ..................

....... .............................. ........... ...................................... ...............

..

.........................

.........

..... .......... .. ...........

..

............ ........

........... .........

.. ................................................ ......... ......... ...

...

........ . . ......................... .......

.......

.
.

....... . ..

. . . . . . ....

...................................... .... .......... . . ....

......................................... ........... .............................

. . .... .............................. ......................................

............................................................... .......................................

1.3.1. Dalvik Virtual Machine


1.3.2. Core Libraries .
1.4.
1.5.

.............. ........................................................................

.......... ......... ..... ... .......

...

.... .... . . . . . . . .

. .

........ ......... . . ......................

... . . ................ ... ....... .......................................... . ......

. . .

................................................................... . . ....... ... . . . .............

2.

12
13
13
14

................................................................................ 15

2.1. .
2.1.1.
. .
.
2.1.2. JDK .
2.1.3. Eclipse
2.1.4. Android SDK
2.1.5. Andr:>id Development Tools

15
. 15
16
l7
17
18

................................... ................... . . ............................

.......... ... ..........

............................................ .............

.. ............. ............................................ .....................................

............. ............................................

..

. ..................................

.......................................... ........................................

................................................. ..........

IV

2.2. Andoid SDK . . .. . :.......................................................................................... 2 1


2.2.1. SDK Android ! Level . . ... . .
. .. . ..
..
...
21
2.2.2.
.
22
2.2.3. Android Virtual Device
.
23
.. .

. .

... ....

. . ........ .

.. ..

........ . .....

..............

...... ............................

................ ............. .........................................................

3.

3.1. Eclipse
3.2.
. .
3.2.1. .

Android.....................

. .. . .
.
.. . . .. .. .
. . ...
res/layout/ .

......... ...................... 31
.

31
. 35
36
37
res/drawaie/
37
res/values/
. ..
.
37
3.2.2. R.java ........................................................................................................ 38
3.2.3. HelloAndroidActivityjava . . . .
... .
... . . .. . . 39
3.2.4. AndroidManifest.xml
... ... . ... ....... .
. ..
. .. . .. . .. . 40
.... .

........ .. .......

... . ......

. .. .

...

. .... ... . . . .
. . . .
.
.... .. .... .
.
.. . ..
.
.

....... ..

... ....

.. . . . ...... .. ... .. ....... ................

.. ....... ............

.. ...

..

.....

....... .

.. ........... .. . . ..... . . ...... ..................... . .. ...................... ...........

.. ..................... ......................... ......................................

.......................................... ........................................

.......... ....... ..... . . . ................................ ... .......................

.. .... ... .. ................ . .

.... . .

4.1.
4.2.
4.3.
4.4.
4.5.

. ....

...

. ..... ..

.... .........

........... .

. .. ..

. ....

.. .....

. ....

.. ..

4. ndrid- .................................................. 43

43

44

.
..
44
- ..
..
.
..
.. . .
.. 45
. .
. .
.
. . . 45
4.5.1. . . . . . . . ...
.. ...
.
. 45
4.5.2. .
.
.
46
4.6.
48
4.6.1. .. . . . .
.
. . 49
4.6.2.
.
49
4.7. AndroidManifest.xml .
. ..
.
.
49
4.7.1. . .
. .
. .
51
<manifest> . ..
. . . . . .. .
. ..
. . . 52
<permission> . . . . . . . . . . . . . . .. . . . ...... . . .
. . . 52
<uses-permission> . . ........ . .... . .. . .... .. . . .. . ... .. . .
.. . 53
<permission-tree>
.
. 53
<permission-group> .
. .
.
. .
..
. . 53
<instrumentation>
.
..
. . . . . .. . .
. . . 53
<uses-sdk> .
..
.
. .. . .
.. . .
54
<uses-configuration>
. .
. . . ....
.
. . . . .. . . ...... .......... .... 54
<uses-feature>
. .
. . .. . ..
..
.. . .
. . . . . . .. 54
<supports-screens> ...
.. . . . . .... .
. . . .. . ..
.. .
.
54
4.7.2. <application>
55
<activity>
.
56
<intent-jilter>
..
56
<action> . . . .
.
. .. ... . . .. .. . .
.. 56
........................................ . . .......................... . . . . .......................................

...................................................... ..................................................................

....................... ...................... . ..........

...........................

..... ....... . .... ...............

... ... ....................

. . ........................ .. . .. ......... ................. . . . ............................ .... .

. ..... ... . .... . ... .

..................... . ..... . . ..... ..... ..

. .. ................. ............... . . . .......... ......................

.............................................................

.... .... ... ..... ................. ....................................... .

..... ..............................................................

. ........... ..

...... .................................. ..............................

..... .............. .... ................... .. ..........................

.... ...

.................. ... ... . ... ..

. . .... .. . ... ... . ....

... .... ...

. ..

... ............ .. . ...... ....................... . . ..

.. .... .

. .

.... .. .. ....

.. .

....

.... . .

..... .... ..

... ................ ... ..

. ....

...

.. . .......

. .

.............................. ....................................... ..................... ..

.................... .... ...... .......................... .....

........ . ....... . . . .

............................... ...... . ................. ... . .... . ..

............

...... ........ ...

.... .... .......................................

......... ... ......

........... ... ......... . . .

....

........

.. .

. ..... .

..... ...... . . .. ..

..... . .. .... . ..... . ........

. . .. .

.. ....... .....

.. .

... .

. .. ..... . .. ..

.. . ..............

..

.. .. ........... . . . ... . .

.. .

......

... ......

..

...........

.................. ............... ......................... ........

................................................................................................. .........

................................................. ................. . ................................

.. .. ..... ... .......... ............. ............. ..

.. .

...

..

. . ...........................

<category> .
.
.
. .
. ..
.
.
.
57
<data> . . . . . . . . . , .............................................................................. 57
<meta-data> ... . ..... .. . . .. . . . .
.. . .. .
. . ..
. .
57
<activity-alias> . . . .. .. .. . . ..... .. .. . ...... .
. .
.
. . . 57
<service> .. .. . . . . .......... . .
....
. . . . .. ... . . . . .
.
. 58
<receiver> .. .... . . . .... ...... .. . .. .
.. . ... .. . .. . . .. . ..... . . . 58
<provider> . .
... .. .. . . .. ..
.... .. . . . ...... . ..... .. .. . . ... ... . ..... 58
<grant-uri-permission> . .
. ...
. .
.
.
.. . . . .
. . 58
<path-permission>
. .
.. . 59
<uses-library> . .
. . ... ..
..
.. . . .
..
59
......... ............. ..... ... .......................... .. . ...... ....... .............. ........

. .. .. . ..... .... .... .....

. ....

..

....

...

..

. . ..

.... . ...

. ... . ...

.. .. ... . ..

..

. . ......

.. .... . ..

. .. .......

...... . ... .. . ..... ........ . ..

... . ...

..

. .

. . .

.....

... . ...... ..

...

. ..

........ . ... .. ...

... .........

.......

........... .. ...........

.... ......... ..

.. ..

..

............... ..... .. .

. ... .. . . ............ .......

.... .

.. . ..... .

. . .

. .

..

.. ...

..

.............. ..... ........ ...... ......

. ... .... .

. . .

. .

.. .. . .... ...... . .

..................... ............................................ .... ............

.. ...... .... ....

5.

..

...... . ...........

..... .. .... .....

... ....

..............................

........................................... 61

5.1.
..
.
..
5.2.
5.2.1. XML . . .. . . .
. . .. .
.. . .
. . .
5.2.2. L- .. .
.
.. . .
.
5.3. .. . . .. ... ..
.
.... . .
5.4. . .
. . . . . .
..
5.4.1. FrameLayout
..
.
..
.
.
.
5.4.2. LinearLayout
5.4.3. TaleLayout .
. ... ... . ...
. . .
.
5.4.4. RelativeLayout . .
. . .
. .
.
.
5.5. Hierarchy Viewer
5.5.1. Layout View
.
.. . ..
.
... .
.
.
.
5.5.2. Pixel Perfect View.
. ........ . . . .. .
..
.
.
.
...............

62
62
64
65
67
68
68
70
74
78
81
82
. 83

..... ........................... . .................................... .....

.............................................. . ........................................................................

. .

. . .. ..... ... .

.. .............

... ........ ...........

.. .... .

...

...

.
..
..
.
.

.. ..... ............ .. .... ........... .....

... . ........ ...... . ........ ......... .... . ...

................... . ... .....

.. .. .............. . ..

.
.

.. . .................... ... .. ..... .. ... ......................... . ........... .... . . ...

.......... . ..... ..........

. ...... .

....

. ..

.............

......... ........................... . . .

..... .... .....

.................... .... .... ........ ....................................

... .... ....... .... ... ........ .. ............... ........................... ..................

............................................ ......

........... ........

. .

........ ..

....... ......

.... . ... .

.
..

. .............................. ...... ...... .. ....... ..

... .................

...... ....... ........ ..........

6. ................................................................................ 85

6.1. .
.
..
6.1.1. TextView .
.
.
..
..
..
...
6.1.2. EditText .
. .. . .
. .
.
6.2.
. . .
6.3. .. .
..
6.4.
. . .. . .. .
.
6.5. ..
.
..
. . .
6.5.1. Button
.. . . . ..
.
....
6.5.2. RadioButton RadioGroup . .
6.5.3. CheckBox .
.. . .
6.5.4. ToggleButton
6.5.5. lmageButton
.. . .
.
6.6.
.
.
..
.
.. .
6.7.
.. .
6.7.1. ProgressBar .. .. .
..
. .
6.7.2. SeekBar
. . ..
.
.
6.7.3. RatingBar . . . . . .
.
..

. .

.. . 85
86
.
90
.
. 92
.
95
. 97
.
98
. . . . 99
. .
106
.. . . . 109
112
..
115
117
.
120
.
121
125
. . 129

.... .......... ............... . ........... . . . . ........ ................ ..... ... .......... .....

...... ..... .....

..... . .......

........

... .

............................. ..............................

.
.

.... ..... .. . .. .... ............ .. ........ ..................... ...... .................. ..............

............. .. ... .............................. ..................... ......... .

...

... ......................

..... .... ..

.......

.. ..

.. ..
..
.
... .
.
.
..
...
. .

.........

. ................. ..

..

.......... ...... . ...... ..... .... ..... ..........

. ... . ....

........ ...........

..

.......... .......... . .................. .....

.................. ............................... ....

.. .............. ........ .................

........ ......... ................................. .... . .... .

.
.

..

... .. ................. . ............... .......

.. .................. . .. .. .....................

...............

.......... .... ..........

......... ... .. ..................... . . ..

. .... ....... ........................ . . ........... ..... .........

........ ......... ..... . . . ...... ........

..

. .

... . .

...............

.... ............... .... . .... .. .......... .................. . . ......

.
.

............... . .... ............. ............ .............. ......... .................

..

. ........... . ........... .. ...................... ......... . ..... .................. .......

..

......... .. .. . ................. . . ......... ........

.. . . .. .... . ...... .........

............ ............. . . .......................

............ . . ........ ....................... ................. . . .. .

Vl

6.8.
6.8.1. AnalogClock Digita/Clock. . . .
6.8.2. Chronometer .. .. .
.

.. .

.................. .....................

. ....................... .....

133

. 134
. 135

.. .. . ........................................... ...................... .

. ................ ............................................. ................. ........... .

7. -

... . . .. .. ......... ..... ... 139

. ... ...

..

...

..

7.1.
..
. .
.
.
. 139
7.2.
. . .
.
.. .
140
7.2.1. AutoCompleteTextView
. . . .. . .
..
. . .
.
140
7.2.2. MultiAutoCompleteTextView . ..... .
.
.
.
.
143
7.3. .
... . . . .
146
7.3.1. ListView ............................................................................................................ 147
7.3.2. Spinner.... . . ..
.
. . ..
. .. .
. 149
7.3.3. GridView. .
..
..
.
. ... ....
153
7.4. .
. . .
.
157
7.4.1. GridView ...........
.
.
. . . . . . 15 7
7.4.2. Gallery
.. .. ... ...
. .
..
. .. . .. .. . .. 161
7.4.3. SlidingDrawer .
.
.
. .
.. ..
.
.. . .. .. 164
7.5.
. . .. . .
. .. . .. ... 170
.....

...................... ..... ...... ....................................... ................ ..

...................... .. .... ..... .........

.................... . . ....

.. .....

..... ...................

..... .... ....... . ....... ..... .. ........ .......

. ........ ............. ........... ..................... ....

. .......... . . .. ... .. ..... ..............................................

. . .

......................... .................................... .. .. . ....... ..

... .........

..........

........ ..................... ................ .

....

. ............ .

....................

..................... .. .... ......... ....................................

, ...... .......... .............. .. .... ... . . ....

....................

....

............. ..... ........................

.... ............ ....... .................. .. .................

......... ..

....

........................ .. ..

8. ......... .

... . .

. .........

.. .

....... ......

.. . ....... ..

..

. ....

. .. .

. . ................ ..

..

. ..

.. ............................. .....

175

8.1.
.
.
. .. .
.
. .. ... 17 5
8.2.
.
. .
. .. . . ... 179
8.3.
.
... .. .. . . . .... . . ..
...... . 182
8.4. . ..
. . . . 187
..................... ...... ............. .. . .. ........ ................

.......... ....... ... ..... ..

............. ........

. .. . .. . .

.... .. .

... ....

9.

. .

.....

..... .. ............

... .

....

..

.. ................

.. ... .

..

...........

........... ..

..

. .. . ..

.. . ... . . . 191

.........

. .

. ... .

9.1. ...................................................................................... 192


9.2. AlertDialog
19 3
9.2.1. AlertDialog ................................................................................... 19 3
9.2.2. A/ertDia/og ................................................................................... 197
9.2.3. AlertDialog
.
.
.. . 200
9.2.4. AlertDialog .................................................................................. 203
9.3. ProgressDialog
.
.
.
..
.
. 206
9.4. DatePickerDialog
.
.
.
.
. .. .. 211
9.5. TimePickerDialog ....................................................................................................... 216
9.6.
. .
. . .
.
.
.
. 219
.................................................................................................................

.......... .............. .........................................

....... ....................................................... ................. ......

. ..

...... .........

...................... ...................... ................. ............. ............. . . . .

..

........... .. ............ .. .... ......... ...... . . ......... ...........

10. . ...... ..... .


.

. .. . .

. ...........

10.1.
10.1.1.
10.1.2.
10.2.
.

..

... .. .....

... .. ........ .......

.. ... . . . .. 225

........

...

.. ... . .

...

226
230
. .. 233

.......................................... ...................... ....... .....................

. ..

. .

..

.................. .... .. . .......... .. ............... . ..... ...... ............

..

....... ................................. ..... ....................

..

........ ..

..

......... .................... ........ . .........................................................

237

V/1

10.3.
10.4.

..................................................................................................................

11.

.....

..................................................

240
244

.... ...................................... ...... 249


.

11.1.
.
.
11.1.1.
11.1.2.
11.2.
11.3.
11.4.
11.5.
..

. 249
253
254
254
257
257
.
271

..................................... ................ ................... ...

........................................................

........................ .............................................................

......... ................................................................................. ......................

................................................. ......... ........................................

.............................

12.

.......................

........................... .......

.................... ...................................... .. ..... ....................... 275


.

12.1.
12.2. . .

. . .

. .
.. . .

275
. 277

...... ................. ... .. ..... ...... ......... ...... ........ ... ...............

..... ............. ............ ....................................... . . ..

... ... ............

13. ........................... 285

13.1. . .
. . . 286
13.2.
..
. ...
.
..
.. . 287
13.3. .
.
... . .. . .. . 288
13.3.1. .
. .
.
. 288
13.3.2.

.
..
. .
..
.
. . . . 289
13.3.3. -
.
.
. 290
13.3.4. - . . . .
. . . . 292
... ... . . . . . .

.....

. ......... . .. ..

.... .. .

.............. ................. . .........

..... ........... ........

.. . .

..

..

. ..

.... .

. ... ....... ... . . . ................. . . ............. ....

................................. ..................

......... .... ...............

...... ......... .. .. ..

......... ............. ............ .... ...

.... .... ... .. .... . . . .. . . .

..... ... .

14.
....................................... .............. ....................................................... 295

14.1. .
..
.
.
.
.
.
14.2.
.
. . . .
. . .
.
..
14.2.1.
. . ..
.
. ..
14.2.2. CheckBoxPreference
.
.
.
14.2.3. EditTextPreference
14.2.4. ListPreference
.
..
. ..
. .
14.2.5. RingtonePreference
.
.
. .
..
. .
14.2.6. PreferenceCategory
.. .. . .
.
..
14.2.7. PreferenceScreen
.
. .

295
. 301
302
. 303
310
312
. . 315
316
. 317

..... ....... . .................. ....... ............... ...... ........... ............

...... ............... .. ..... .. ..................... ..... .. .......... ........... . ............. .

...... .. ..

................ ......... .

........................

.......... .................................... ....... ........................... .

................... . .. . ................................................................

................................ . . .......... . ...... ...

............ ..... ................

........ . . .............. ....... ..... ..............

......................

.....

...... .. ............. . ....

. ... ....... ...............

........................

......................... ........................... ..... ......... .................. ..

15.

SQLite - ....................

15.1. SQLite
.
.
15.1.1. : SQLiteOpenHelper .
15.1.2. : SQLiteDatabase

.... . .. 323
.

........................................... ................ ....................................

.. ....................... ..........

...... ............

...............

323
323
325

V/11

15.2. -n ............................................................................................... 326


15.2.1.
.
.
.
.
.
.
. 327
15.2.2. URI .
.
.
..
.
.. .
.
.
327
15.3. -n
.
. 328
15.3.1. ContentProvider .......................................................... 329
15.3.2. -n . .
. 331
15.4. n t-n
.
331
15.4.1.
.
. .
.
. 332
15.4.2. ....................................................................... 333
15.4.3. n
.
.
.
. . 334
15.4.4. n ....................................................................................... 334
15.4.5. n ........................................................................................ 334
15.5. n . .. . . .
.
335
........ ..... ............... ................... ........... ........ ................. .

... .............. ............ .......

.................. .......

. ................. .............. .......

...................................... .......................................

... .. ..............

........ .....................................................................

....... ........... ... ............ ..........................

.......................... ....... .................................. ......... .. .

.. ....

1 6.1.
16.2.
16.3.
16.4.

16. ,

.. .... ... ...... ...........

.......................... 349

n n ........ ..... . ........ .......... . .... ..


. .. . .. . . . ... . 349
..... . .. . . . . . .. .. . .. .. .... . . .
.
. . .. .. . .. . 350

.. ..
. .. ... . . . ... .
. . . .... . . . . . . .
351
n ......................................................... 352
16.4.1. n ..
353
16.4.2. n
.
. 358
16.4.3. XML
. 360
16.4.4. L- ......................................................................... 364
16.5. .
. .
..
.
.
368
16.5.1. .
.
.
.
368
16.5.2. ............................................................................................................. 369
16.5.3. n ................................................... 370
16.6.
373
16.7. . . ... . . . ..
.. .. .. . . .. .... ..
377
16.7.1. , no .. ... ...
. .
.
.. 377
16.7.2.
.. ..
.
.. . .
378
.

. ...

... ...

...

. .

. .

. . ... .

. ...... ... ... ...

. . .. . .

..

..

........ ...

... .

..

. . . ..... . ..... ... .

. .. .

... .

..

......... ..... . .

.... .

..

.. .

.. ..

... . . .... .... .... . ...........

.....................................................

............... ......................................

................ ..............................................................

.... ............. ................... ..... ................

....... ............ .... ....................

.. .......... .............................. ................. ........................... ..................

.....................................................................................................................

... ....

.. . . . .. .

.............

....

..

....

.........

. . ...

....

....................

....... ... ......... ....................

...

............ .....

..... . . . ...........

17. ............................................................................................. 381

17.1. Drawa!e .
. .. . . . . .
.. .. . . .
. .
.. .
. .
381
17.2. Drawa!e n. ..
.
.
. . 383
17.2.1. TransitionDrawa!e .... . .. . .. ... . .. .. . . . ... .
. .
384
17.2.2. ShapeDrawa!e.................................................................................. 386
17.3. .... . .. . . . ... .. ... . . .. .
. ..
. .. ... ...
393
. ..... .

.. ..... .. . . ......

. ... . ...... ... ............. . .. ........ ... ............

....

. ..

. . . ..

.. . .... ..

. .

..

.... .. .

...

...

.............. ........... ..... .... .....

... .. . .

.....

....

... ........... .. .............

............... .

.........

18. ......................................................................... 4 01

18.1. n .. .... ..... . . ... ..


..
. . .. ... . . .. ..
..
401
18.1.1. L-............................................................. 402
....... . . .. .
..
. .. ... ..
. . .. 403
<set> . .
. .. .
.
. . ... . . .
.. . .. . . ... . .. . . 404
....

..

. ... .

. . .

. ........

.... .. ......... . . .. . . .

..

.....

....... . ....

......... .

...... ...... ... .

....

..

...

. . .

...

........

.....

.......................... ... ..

. . . .......

. .

. . .

. ...

... .. .

IX

<alpha> . . .
.... .
.
<scale> ... .
. .
.
<translate> .
.
<rotate> .. . . . . .. . ... .
18.1.2. n
18.1.3.
18.1.4.
18.2. .
.
.
18.2.1. XML
18.2.2. n
. .. .... . . .

. ............ ..... . . . . ...

404
404
405
405
405
413
. 417
421
422
425

......... . . .......... . ..... ....... .........

... .......... ... ........... ....... . . ...... ..... . ..................................

. . . ......... ..................... ........ ............... . .... . . . . ........ . ... . . . .

. . .. . ...

. ..

.
. ...

. ................. ............. ...... . . . . . . ......... ...........

.......... . .

. . ....

..

..... .

........ . . ............ . . ..

............................ . .. . . . .... . ...... ............. . ......

................................... . .... . ...................

.... ............ . . . ........... ...................................... ........... . . . . . . . ........

..................... . . . . ... . . . . ......... . . ............

............. ............. . .... . .. . . . ........... . . . .

. - .............. 429

n-

....... . . . . .... . . ............................................. . .. . . . . .............. . . ..... .....

........................................................................................................

429
429

. .............. ..... .......... .. ........... .......... ....................... ........ 433

Goog\e Android

.
,
, Android.
Android?
Goog\e ,
,
SDK,

. Android
.
- Google
Adroid . Android
, .
Google Android ,
.
Goog\e Android
2008 - - Android Market,

. ,
Android Market,
.



Android, -

Java,
Android SDK.
, Java,
- ( C#.NET),
Android . Android

I-, Android SDK. ,
Java
Androi d .
Java ,
Android.
:
D ,
Java C#.NET
Android;
D ,
iPhone, W indows Moile, Symian JavaME,
Android.

, ,
Android. ,
, .

,
. , ,
.


1 8 .
.
D 1. Android


Android.
Android, ,
Android SDK.
Android, Dalvik V irtual Mach ine.
D 2.


, Android: Java

Development Kit, Ecl ipse, Android S DK, Android Development Tools,


n n Android.
n , Adroid SDK, -
, n, n
n .
no Android Virtua\ Device -
.
3. Adroid

n n n Android, n
n .
n, n
Ecl ipse.
4. drid-

ndrid
- , ,
-n.
ndrid-n ,
n .
5.

Android
n n
- pynnax n .
n
n,
)
.
6.


( ). Android - n,
, , , ,
. )
Android.
7. -

-n,
,
, n - -
n
.

D 8.

.
,
.
, ,
.

. -
.
D 9.

Android.
, ,
.

.
D 1 .

Android SDK .
,
Android, , ,
, .
D 11.

-
.
ndrid- .
.
And
roid - . -
.
Android
, .
D 12.

Android. -
,
.
.
D 1 3.


(Broadcast Receiver). -

, ,
,
.
1 4.

-
,
- .
15. SQLite -

-
.
, Android, - SQLite.
-
.

, - , ,
(
) .
16. ,


. -
ndrid-.
, , , , , L
. .
ndrid-
.
, .
17.


ndrid- .
, L-
.

I-
.
1 8.


Android
Android SDK,
.


,
. .
Android SDK 2.0
Ecl ipse.
2.
,


.
, ,
.
- , , ,
, .

.

" -",
.


An d roi d
Android,

.
Android - ,
,
(middleware),
(-mil- , , , , .).
Adroid :
D

D ;
D ;
D

. 1 . 1 Adroid
.

1 . 1 .

.
,
.
Android Linux 2 .6, Android
Linu- ,
, Android, -
, .

11
.

11

l 1'

'- ------'

Dalvik

. 1.1. Android

:
D (IPC Driver);
D (Android Power Management);
D ,
.

Android.

1.1.1. IPC
,
.
Android I P C (Inter-process Communi
cation),
.

Android

IPC n :

n;

n n n;

n n;

n n .

1.1.2.
n n (Android Power Management)
n n Linux, n
n
.
n n -
n . n
"n " n n,
n n.

1.1.3.
An.droid ,
n n ,
. n n n
n n nn .
n n
( , , GPS, . .).
n
.
n . n
n n ,
n Linux n
n , Linux-cce.
n Linux Android ,
n n
, n . ,
n n , n n
,
n , n , n
.

10

1.2.
Linux /++
OpenGL, WebKit, FreeType, S S L, libc,
SQLite (Media Framework).
Berkeley Software Distribution (BSD) '
Linux.
Linux /++,
.
Appl ication
Framework - .
:

/++.

1 . 2.1. l ibc
Google - ( l ibc) - Bioic.
:

, ,
. Bionic
200 , gl ibc;

.
,
.

Bionic Android
. Bion ic
, ++,
GNU l ibc POSIX.

1.2.2 .
Android ,
Compiz ( W indow System,
3 D- OpenGL).
,
, ,
, .
,
.

A[ldroid

11


. 2D- 3 D-
.
I-.
, .
2D-, Khronos.

. 1 .2 .
Surface

Surface

Surface

Fame

Flinger

Buffer

Surface

. 1 . 2.

1 . 2.3.
Android /++,
.
.
D

(Media Framework).
- .
PacketVideo OpenCORE
- (MPEG4, .264, 3 .).

D SQLite - , . SQLite
-, . . SQLite
, ,
, ,
. ,
(API) SQLite.
,
. SQLite
( , , )
,
.
D OpenGL ES - 3 D-, I
OpenGL ES 1 .0. OpenGL ES -
OpenGL,
. -

12

3 D- ( )

.
D FreeType - ,
.
D WebKit - ,
Android W-. Webit CSS, JavaScript, DOM,
Ajax.
D SGL - 20-. Android
20- Skia,
++ (Skia Google Chrome).
D S S L - ,
SSL: S S Lv .O TLSv 1 .2.

1 . 3 .
Dalvik V irtual Mach ine
( Dalvik),
Jv- .

1 . 3 . 1 . Da lvi k Vi rtual Mac h i ne


,
, Dalvik, t
J ava, . Dalvi k
(
),
RIS-, ARM,
,
Java Sun M icrosystems - .
Google 30
.
Jv- lss-
- Dalvik ( * .dex) dx, SDK.
Android
Dalvik, .
Dalvik,
Google Android, -

Android

13

,
.

1 . 3.2. Core Libraries


,
Java. API
Jv- Android.

1 . 4 .
,
Dalvik V M .
Android ,
, . .
\,
.
.

, ,
( ).

.
Android - ,
, . :
D (Activity Manager) -

( );
D (Package Manager) -

, ;
D (Window Manager) - .

,
,
. , ,
<Back>
, W-;
D ( Resource Manager) -

, ;

D - (Content Providers) - !,

n ,
;

14

(View System) -
, ,
, , , ,
, W- ;

- API,
,
,
;

- ,

;

-
.

1 . 5.
Android
, , SMS, ,
, , .
, Android
-
, ,
, .
Android Java.

.
, ,
.
.

Android,
. Java Development Kit,
Ecl ipse, Android SDK Android Development Too\s,
Ecl ipse Android.

2 .1 .
Google
(Software Development it), 86-
Windows , OS Linux.

2. 1 . 1 .
ndrid

, .
:
D Windows (86) Vista (32 64 );
D OS 1 0.4.8 ;
D Linux ( Linux Ubuntu Hardy Heron).

Ecl ipse 3 .5
Ecl ipse 3 .4 (Ganymede) :
D Ecl ipse IDE for J ava Developers;
D Ecl ipse I D E for J ava Developers;
D Ecl ipse for RCP/Piug-in Developers.

(Gal ileo)

16

NetBeans I D E , ,
.


:
Ll J DK 5 6 ;
Ll Ecl ipse I DE;
Ll Android SDK 2.0;
Ll Android Development Tools (ADT).

SDK, Java Ecl i pse W i ndows, OS


Linux, ndrid-
, . SDK
, , ndrid-
,
.

M i crosoft Windows

2. 1 .2. J D K
n Java
.
, ,
Sun Microsystems.
Java Runtime Environment
( Java, JRE).
- JDK (Java Development
it). J ava Development K it -
Java, Java Uavac),
Java, , ,
Java Runtime Environment (JRE). Java Development Kit
Sun M icrosystems
http://java.sun.com/javase/downloads/index.j sp.

JDK 6 U pdate 1 7
JDK 6 U pdate 1 7
with J ava .

17

JDK ,
.
JDK Java
(IDE), Eclipse.

2. 1 .3. Ec l i pse
- Ecl ipse.
Ecl ipse http://www.eclipse.org/downloads/.
Ecl i pse,
. 2. 1. 1 ( Ecl i pse IDE for Java
Developers).
Ecl ipse,
ecl i pse.exe. Ecl ipse
( M S Windows), Program Fi les
.
IDE,
, Ecl ipse ndrid
:
D Ecl ipse - ,
Java. Eclipse
- . Ecl ipse
IDE Android;
D Google Android Eclipse
Android Development Tools, Android-poe,
Android-ycpoca
. Android Development Tools
Ecl i pse Android
poea .

2. 1 .4. A n d roid S D K
Android, Android SD. SDK
,
Android, Android.
- Android SDK v2 .0. Android SDK
Android
http://developer.android.com/sdk/index.html.
.
2.0 Android SDK .

18

SDK
Android. 2.0 Android SDK and VD
Manager, SDK -
, , .
,
Android, Android SDK and VD Manager.
, . .
SDK Google.
Android SDK and V D Manager, n SDK
Setup.exe SD. n
n n n, n
. 2 . 1 .

v SDK Platform Android 1 . 6, API 4, re . . .

Google AP!s Google Inc . , Andro1d . . .

v SDK Platform Android 1 . 1 , ! 2 , r e. . .


v SDK Platform Android 2 . 0, API 5, re . . .

Google AP!s Google Inc . , Android . . .

? Usb Dr1ver package,

revi 10n 2

V Documentation for Android SDK, ! . . .

. 2 . 1 .

n, n Install Accepted ,
, n SDK.
Android SDK n D-n Ecl ipse.

2 . 1 . 5 . A n d roid Development Tools


Android Development Tools (ADT) -
Ecl ipse,
.

19

Android Development Tool s Eclipse,


Help 1 Install New Software.
Add .
ADT, . 2.2.

. 2.2. n ADT


Eclipse.
Ec l ipse Android SDK.
Ec li pse Window 1 Preferences,
Preferences. And roid . SDK
Location ,
Android SDK. Browse
Android S DK, . 2 . 3 .
Apply, . IDE Ecl ipse ""
Android SDK,
Android.
D- Ecl ipse
Android,
Ecl ipse, ,
.

20

Build
DDMS
Launch
LogCat
Usage Stats

fii

Android 1 . 1
Android 1 . 5
Android 1 . 6
Android 2 . 0
Google AP!s
Google APis
Google APis

Ant

fii Data Management

fii

'*

Help
Instaii/Update
Java
Java

Android Open
Android Open
Android Open
Android Open
Google Inc .
Google Inc.

Source
Source
Source
Source

Project
Project
Project
Project

Google Inc.

1 .5
1.6
2.0
1 .5
1.6
2.0

4
5

Plug-in Development

fii Remote Systems

fii
'J

Run/Debug
Server

fii Tasks

rti

Team
Terminal

r1:i

Usage Data Collector


Validation

fii Web

r1:i
;tJ
fii

Web Services
XDoclet
XML

. 2.3. Eclipse Android SDK

D- Ecl ipse :
L] Android - New Proj ect Wizard,

Android ;
L] Layout Editor -

;
L] , -

L- .
D- Android
Ecl i pse. , ADT
, DDM S (Dalvik Debug
Monitor Service) - SDK ,
(breakpoints),
Ecl ipse.
.

21

2 . 2 . A n d ro i d S D K
Android S DK ,
,
Android.
D API Android SDK - I- Android,
.
D SDK - ,
,
.
D AVD (Android V i rtual Device) -
Android. ,
Android-ycpoca.
D Development Tools - SDK

,
.
D Sample Code - Android SDK ,

Android,
, ,
API .

2.2. 1 . S D K And roid API Level


Android
API .
Android API Level ( API)
,
.
API - ,
API Android. API,

Android. Android
API.
I- , API
API. ,
API
. API
, API ,
.

22

API, Adroid,
,
drid-.
7 API.
. 2 . 1 API Adroid.

2. 1 . /

API

A n d ro i d 2 . 1

And ro i d 2 . 0 . 1

Android 2 . 0

A n d ro i d 1 . 6

A n d ro i d 1 . 5

A n d ro i d 1 . 1

Android 1 . 0

2 . 2 . 2 .

, SDK ,
.
Adroid I DE Ecl i pse,
, S DK,
. S DK
:
D

adroid - ,
, ,
, drid- (
Ecl ipse) Adroid SDK ,
;

Dalvik Debug Mo itor Service (DDMS) - Dalvik V i rtual


Macl1 i e, Adroid,
,
.
,
, , " "
,
;

23

Hierarchy V i ewer - ,

. ,


;

Layoutopt - ,
.

, ;

Draw 9-patcl1 - ,
N i tl1-
;

sq l ite - SQLite,
Android;

Tracev iew -
, ;

mksdcard - ,

(, SD).

, ,
.
- ,
S DK ,
.

2.2.3. And roid Vi rtual Device


Android V i rtual Dev ice ( Adroid) - ,
.
,
.
ndrid- ,
Android V i rtual Device ( V D). VD
, .
:
1 . android, ,
Adroid S DK, i too ls.

24

2 . Android SDK and V D Manager IDE Ec l i pse,


Window 1 Android SDK and VD Manager.
And roid SDK and VD Manager,
,
Android SDK (. 2 .4).

Android S D K and AVD Manager ,
a n d roid . exe .

. 2.4. Android SDK and AVD Manager

List of existing Android Virtual Devices


New, C reate new VD (. 2 . 5 ) .

:
LJ Name - ;
D

Target - Android S DK, .


SDK, . .
Adroid 2 .0, SDK 1 .6,
1 .5, 1 . 1 ;

SD Card - SD;

LJ Skin - .

, -

25


.
SDK, Target,
, :

HVGA (alf-size VGA Video Graphics Array), 32480,


, ;

WVGA800 (Wide Video Graphics Array), 48 800,


, ;

. 2.5. AVD

WVGA854 (Wide Video Graphics Array), 48 8 5 4, ,


;

QVGA (Quarter Video Graphics Array), 24 3 20,


, ;

WQVGA (Wide Quarter Video Graphics Array), 24 400,


, ;

26

Hardware - , .
New
n (. 2.6).

. 2 . 6 .

n C reate AVD ( . . 2 . 5 )
, API
List of existing And roid Virtual Devices
( . . 2 .4).


a n d oid . exe . , AVD
g, ,
. , -
.

API
. 1 . 5 ,
. 2 . 7, 1 .6, 2 . 0, 2. 1 ,
. 2 . 8 .
.
. 2 . 8 .
Home screen - Android.
.
-
.
,


( - ).
.

27

. 2 . 7 . AVD 1 . 5

. 2 . 8 . AVD 2 . 0

28

2

SI
<Cti>+ < F 1 1 >
.

- Status Bar.
: ,
. Status Bar
( , )
,
,
, . Status Bar
,

.

- Application Launcher (. 2.9).
.
, , ,
:

.
;

. 2.9 . Application Launcher

29

D USB;
D ( );
D ;
D ;
D ;
D

SD;

D 8 \uetooth .

, ,
VD
.


And roi d
,
,
, "Hel lo,
Android ! "

3 . 1 . Ecl i pse
Android ,
Ecl i pse. Ecl ipse
File 1 New 1 And roid . And roid Project
Next (. 3 . 1 ).
New And roid Proj ect (. 3 .2).
:

Proj ect name - He l loAndroict;

Application name - He l l o ,

Package name -

And ro i d !

Samp l e ;

s amp l e s . he l l oandroid;

C reate Activity - H e l J_ oAnd roidAc t ivity;

Build Target - Android

Min SDK Version -

1 . s;

.
Project name - Ec l ipse - ,

Application name - - ,
.

32

Select

wizard

& Class
fi Interface
Java Pro}ect

!1

;j;j

Java Project from Existi"'l Ant Buildfile

;J& Plug-in Project


Q:i. General
Q:i. Android

ill3 dd'I
Jci1 Android Test Project
. Android XML File

00 1:7 Connection Profiles


;! l.ii& cvs

. 3.1 .

Package name - ,

, J ava.
, , Ac t ivi t y,
.

,
Adoid.
.

C reate Activity - ,

. Ac t i v i t y .
,
, Ac t i v i t y .
Ac t iv i t y 4,
ndrid-.
Use default location - ,

.
Min SDK Version - A P I ,

33

Android

New Android Project


Creates new Android Project r

1 .5
1 .6
1.6
2.0
2.0
2.0. 1

. 3. 2. New An droid Project

Build Target -

API ( ,
SDK Min SDK Version).

API
.

A P I . AP I , , AP I ,
, .

34

B u i l d Target A n d roid 1 . 5
( M i n S D K Vers i o n - 3) . ,
n Android 1 . 5 . A n d roid
, , A P I 1 . 5 ,
1 .6 , 2 . 0 , 2 . 0 1 2 . 1 .

Finish . New Android Proj ect .


Package Explorer .
D-
, " Hel lo, World" + (
), Create Activity.
, , "Hel lo, Android ! "
stri ngs.xm l , res/values/,
Resou rce Editor
XML < s t r ing
name= " he l l o " > :
< s t ring name= " he l l o " >Hel l o , Android ! < / s t r ing>

Run . Run As
. Select way to run 'HelloAndroid' Android
Application (. 3 .3 ) .

2_elect

way t o run 'elloAdrold':

i!tiiID
gnd
_r

roid JUnit est

Java pplet
Java pplicati
,Tti JUnit Test

Desription

Runs an ndroid App&cation

. 3 . 3 .

D- Ecl i pse
,
.

35

Android

, MENU.
(. 3 .4 )
.

. 3.4. "Hello, Android' Sample"

. "Hello, Android ! Sample",


, - .
- ,
strings.xm l .

3 .2 .
D-
, Java. Ecl ipse, Package
Explorer, (. 3 . 5).


AP I , . , 7 ( Adroid
2 . 0 ) res/ d rawa e/ : d rawa e
h d p i/, d rawae-m d p i/, d rawae-l d p i/
.

36

src

com. samples.helloandroid
lfi.. 0 Hellondroidctlvity. java

!! gen [<;e;.er,ted .J File;]


liil

!!:

com.samples. helloandrord

ilJ R . java
:iJ W. ndroid 1 .5
. ... assets
res
::.0 2& drw
.
iJ icon. pnQ
lti

!i:il 2&

layout

8 (i&,

values

i)t

main.xml

LJt strings.xml
<Qi ndroidManifest . xml

[@ default.properties

. 3.5. "HelloAndroid" Package Explorer

bin/.
Jv-
apk.
.
.

, .

3 . 2. 1 .

: , , .
ADT- , ,
.
:
D res/drawaJe/ - (PNG, JPEG . .);
D res/layout/ - L- ( );
D res/menu/ - L- ;
D res/values/ - , . .;
D res/xm l/ - L-,
.


. -, Android
res/. ,
n nn L-
( res/).

Android

37

res/layo ut/
XML,

.
TextView ( 3 . 1 )
.

< ? xrnl ve r s i on= " l . O " encoding= " ut f - 8 " ? >


<Linea rLayout xmlns : andro id= " http : / / s cherna s . android . com / apk / res / andro id"
android : l ayout _wi dth= " f i l l _pa rent "
android : layout _hei ght= " fi l l_parent " >
<TextView
android : id= " @ +id / TextViewO l "
android : l ayout _width= " fi l l _parent "
andro id : layout _he ight=" wrap content "
_
android : text= " @ s t ring / he l l o " >
< / TextVi ew>
< / LinearLayout>


- 6 7.

5,

res/d rawa ie/


,
. icon .png -
,

(Application Launcher).

res/va l u es/
: ,
, , . . ,
"Hello, Android ! " ,
:
D ;
D strings.xml he l l o " Hel lo, Android ! ",
android : t ext TextView
strigs.xm l , 3 . 1 :
a n d r o i d : t e x t = " @ s t r i n g / he l l o "

38


3 .2 .

< ? xml ve r s i on= "

. 0 " encoding= " ut f- 8 " ? >

<resources>
< s t ring narne= " he l l o " >He l l o , Android ! < / s t ring>
< s t r ing narne=" app_narne " > "He l l o , Android ! " Sarnple< / s t r ing>
< / res ource s >

3.2.2. R.java
, R
R.j ava.
, res/.
R.j ava 3 . 3 .

AUTO-GENERATED FILE .

DO NOT MODI FY .

Th i s c l a s s was automat i c a l l y gene rated the


aapt toQl from the res ource data it found .

It

should n o t modi fied hand .

pac kage com . arnple s . he l loandroi d ;


pu l i c f i n a l c l a s s R
pu l i c s t a t i c final c l a s s a t t r
pu l i c s ta t i c final c l a s s drawale
pu l i c static final int i con=Ox7 f0 2 0 0 0 0 ;
pu l i c s t a t i c final c l a s s id
pu l i c s t a t i c fina l int TextVi ewO l=Ox7 f0 5 0 0 0 0 ;
pu l i c s t a t i c final c l a s s layout {
pu l i c s t a t i c final int main=Ox7 f0 3 0 0 0 0 ;

39

Adroid
pul i c s t a t i c f i n a l c l a s s s t r ing
pu l i c s t a t i c final int app_name=Ox7 f 0 4 0 0 0 l ;
pu l i c s ta t i c final int hel lo=Ox7 f 0 4 0 0 0 0 ;

R ,
res/:
Ll

d rawale -

Ll

l a yout - res/layout/.
. - main.xm l ,
.
,
;

Ll

id - ,
main .xm l ;

Ll

s t r ing -

res/drawa\e/;

strings.xm l .

R,


, . .
.

3 . 2 . 3 . Hel loAnd roidActivity.java


, A DT-
() .

He l l oAndroidAc t i vi t y -

onc reate ( ) ,

. ,
n .
He l l oAndroidAct ivity,
3 .4 .

pac kage com . s amp le s . hel loandro i d ;


import android . app . Activi t y ;
import android . os . Bundle ;

Ac t ivity,

40
pu i c class He l l oAndroidActivity extends Act ivity
/ * * Ca l l ed when the activity i s first c reated .
@ Ove r ride
pu i c void onCreate ( Bundle s avedins tance S tate )
s upe r . onCreate ( savedinstanceState ) ;
set ContentView ( R . l a yout . main ) ;

,
, Ac t ivity.
,
.

3. 2.4. And roidMan ifest.xm l



L-,



AndroidMan i fest.xml .
: , ,
( Android,
), , .
3 . 5 .

< ? xml ve r s i on= "

. " encoding= " ut f- 8 " ? >

<mani fest xmlns : android= " http : / / s chema s . android . com / apk / res / android"
android : ve r s i onCode= " l "
android : ve r s i onName= " l . O "
package= "com . s amples . he l l oandro i d " >
<app l i cation
android : i con= " @ drawal e / icon "
android : labe l= " @ s t ring / app name " >
_
<act ivi t y
android : name= " . He l loAndroidAct ivi ty"
android : l abe l= " @ s t ring / app_name " >
< intent - f i l ter>
<act ion android : name=" android . intent . ac t i on . AIN "
<category android : name= " android . intent . category . LAUNCER" / >
< / intent- f i l ter>
< / a c t ivity>

Android

41

< / app l i cation>


<us e s - s d k andro id : minSdkVe rs i on= " "
< /rnanifest>

, android : name <activity>


() .
i con l abel , ,
.

Act ivity,

.

, ndrid-
.


nd r i d -
Android ,
, .
Android ,
( ,
).
,
.

,
, .
, ,
Android ,
, , main ( ) -
. ndr id- ,
.
ndrid- :
D (Activity);
D (Service );
D

(Broadcast Receiver);

D - (Content Provider).

4. 1 .

- . ,
, , . -

44

,
,
, -
.

. n n n
n . n
n.
n
. Android n n
n - n, n, , n ,
. . n
5, 6 7.
n Act ivity (
n n n ,

He l loAndroidAct i vi t y) .

.
. n
n,
(
1 1) .

4. 2 .
n n
n n .
, n .

n ,
n, n .
, , n
.

4. 3 .

-
. n
n . n
, ,
.

Android-npuoe u

45


. ,
, ,
.

4.4. -
- ,
, .

, SQLite
. -
. ,
-,
-
.

4. 5 .
( )
, Android ,
.
.
,
.
.
. ,
,
, . ,

( , )
, . .
. .

4.5 . 1 .
Adroid
, .
, , .
.
Android
, . . ' -

46

,
, , ,
.
, ,
.
, .

4. 5.2.
, ,
. Android
, , ,
, .
, , Android
, ,
(. 4. 1 ).

. 4 . 1 .

.
.
.
D

(Foreground Process) - ,
, .
, :

,
;

, ,
;

did-

47

S e rvice,
, ;

Broadcas tRece iver, .


. -
, .
(Visiie Process) -

,
.
. , , ,
:

, ,
. , ,
, , ,
;

, ,
(
).

,
.

(Service Process) -

,

. ,
, , ,
,

.

(Background Process) -


, .

,
, .
, LRU ( least recently used, "
"), ,
, ,
.

(Empty Process) -

-.
. -

48

, .
.
, Android
.
, ,
, .
,
. , ,
, , .
, -
,
, .
, ,
,
(, ),
, ,
. ,
,
, ' ,
( ) .

,
.

4 . 6 .

- , Android
, , ,
, ,
.
Android ,
. Android
.
,
, (, )
, Android
.

Android-npuoe u

49

, , Android
,
.

4.6. 1 .
,
,
.
- Intent,
. , ,

.
Intent .
- ,

.

4.6 . 2 .
, , ,
. , - ,
,
,
.
, ,
.
,
.
. Android
.
,
Android
.

4. 7 . A n d ro i d M a n ifest.xm l
Android , ,
.
AndroidManifest.xml,

50

.
AndroidMan ifest.xm l .

:
Jv- .
;

D - , ,
-,
. ,
, .
Android ,
;
D ,
API ;
"'Hellodroid nifest

. q;: The appl1catn tag descries appcationlevel components contained 1n the package, as we" as gener 1 apphcation attr1utes.
?.] Define an <applicatlon> tag 11 the AndroidManifest.xml

1\.ppUt:t:it AttribtE':

Defines the attriutes spedfic to the app&cati

lerow . . 1 Per
1 rows . . . .J n
...................] ( rowse j Debugt;)o'ble

' '

Theme

rmiss1

Has code

Appltr..aHon Node

@ @ @ @ ( @ @ :

A t t o ibut es lor <Onolo

od.itent.

Attrbutes that can suppl1ed 11 an AndroidManifest .xml catP.gor-;


tag, chd of the lntent-filter tag.

. 4. 2 .

drid-

51

, ,
;

API Android, ;

, : .

, L-
.
Ecl i pse - Manifest Editor (
),
, . 4 . 2 .

4.7. 1 .
ndrid-,
.
n ,

,
.
. 4.3 ,
, .

<ma ifest>

1
<uses-perm issio >

1

< permissio -tree>
1
<permissio-group> 1
<i stru me tatio>
1 }
<uses-sdk>
1 } API
<uses-cofiguratio > 1 }
<uses-feature>
1 }
<supports-scree > 1 }
<applicatio >
1 }
<permissio>

. 4.3.

52

, ,
. .
<app l i cat ion>
, .
<mani fe s t >, <app l i c a t i on> <us e s - sdk> .
.

<manifest>
<man i f e s t > Adroid
Ma i fest.xm l . Android Ecl ipse
:
<mani f e s t xmlns : andro i d= " ht tp : / / s chema s . andro id . com/ap k / res / androi d "
pac kage= " com . programmingandro i d . he l loandro i d "
andro i d : ve r s i onCode= " l "
andro i d : ve r s i onName= " l . 0 " >,

xmlns : andro i d -

package -

andro i d : ve r s ionCode -

andro i d : ve r s ionName - .

.

Android.
;

,
;
;

<permission>
<pe rmi s s ion> ,

. ,
.
(
, ,
) .
, Adroid ( andro i d . Man i f e s t .
pe rmi s s i on) ,
.
andro i d : name <pe rmi s s ion> :
pe rmi s s ion andro id : name= " com . s ample s . custom_permi s s ion "

Android-npuoe u

53

, :

andro id : label -

andro i d : de s c ription -

andro i d : i con -

andro i d : penni s s i onGroup -

, ;
;

, ;

andro i d : protec t i onLeve l -

<uses-permission>
<use s -permi s s i on> ,

. ,
.
-
andro i d : name .
,
<pe rmi s s i on> , ,
, :
andro i d : name = " andro i d . penni s s i on . CAERA "


android : name= " " andro i d . pe rmi s s i on . READ_CONTACT S "

<permission-tree>
<pe nni s s i on - t ree> .
, ,
.

<permission-group>
<pe nni s s i on-g roup>
.
<pe rmi s s i on> , .
, ,
.
, pe nni s s i onGroup
<pe rmi s s ion>.

<instrumentation>
< i n s t rument at i on> I n s t rumen t a t i on,
. -

54


rls- .
<uses-sdk>

<us e s - sdk>
( API) Adroid.
API, , API
, .
- rninSdkVe r s i on,
API, .
Adroid ,
, API , ,
. , :
a ndro i d : rninS dkVe r s i on= " "

<uses-configuration>

<us e s - con f i gurat i on> n n


.. n,

US-.
, ,
.
n ,
<us e s - confi guration>
.
<uses-feature>

<us e s - feature> ,
. ,
,
.
, ,
. ,
.
<supports-screens>

< s uppo r t s - s creens > ,


( dr id-).

drid-

55

A P I 4
.

4. 7 2 <application>
.

<appl icat i on> - , n


, .
, ,

}
}
}
}
}
}
}
}

---1

<meta-data>

<service>

---1
---1

<intent-filter>
<meta-data>

<receiver>

---1
---1

-1
-1

1
<intent-filter>
<meta-data>

<provider>

-1

1
1
1
1

<grant-uri-permission>
<path-permission>

<uses-libary>

<meta-data>

1
1
1

}
}
}
}

n n
_
n

n n

"-"
n

-n



n

. 4.4. <app l icat ion>

56

,
.
<app l i cat ion>
. 4.4.
<activity>

< act ivity> .


< a c t i v i t y > ,
:
< a c t i v i t y andro id : narne= " com . s arnp le s . he l l oandroid . He l l oAndro i d "
andro i d : l ab e l= " @ s t r ing / app_narne " >,

:
CJ

andro i d : narne -

.
, . .
<man i fe s t >, , ,
, :

andro i d : narne= " com . s amp l e s . he l l oandroid . He l l oAndro i d "

CJ

and ro i d : l abe l -

, .

, < a c t i v i t y>
, , . .
,
, <act i v i t y > .
,
.
<intent-filter>

< i ntent - f i l t e r > ,


, .
-

. -
, ,
, <act i on>,
<category>, <da t a > .

<action>

<act ion>

< intent - f i l t e r >

.
<ac t i on > .

drid-

57

< intent - f i l t e r> ,


. :
< a c t i on android : name= " android . int ent . a ct ion . AIN " >

<category>

< cat egory> ,


. ,
I ntent, :
<category andro i d : name = " a ndroid . int ent . catego r y . LAUNCHER "

<data>

<da t a > .
( mimeType ) , URI
URI. URI
, . . URI : andro id : s cheme, android : ho s t ,
andro i d : po r t , andro i d : path andro id : path Pre f ix, andro id : pathPa t t e rn .

<meta-data>

<met a-da ta> " -" ,


.
<met a -da t a > .

<activity-alias>

< a c t i vi t y- a l i a s > - ,
t a rgetAc t ivity.
, ,
.
.
,
,
.
,

andro id : name = " android . intent . a c t i on . AI N "

android : name=" android . intent . category . LAUNCHER " ,

58


,
.
<service>

< s e rv i c e > .
< s e rvice>
. , ,
. ,
, , , . .
<receiver>

< r e c e ive r>


.
,
,
.
<provider>

<provide r> -. -,
,
<provi der> . ,
, . . .
<provide r>
:
CJ

< g rant - u r i -permi s s i on>;

CJ

<path-permi s s i on>;

CJ

<meta-data>.

, , ,
, . .
<grant-uri-permission>

<g rant - u r i -permi s s ion> - <provide r > .


,
-.
, -,
, .

drid-

59

g rant U r i Permi s s i ons -. t rue,


,
. , f a l s e ,
,
. -
<g rant - u r i -permi s s i on > .

<path-permission>

<pa t h-permi s s i on> - <provide r > .



.
, .
<uses-library>

<use s - l ibrary> ,
.

.
Adroid,
(
Ac t i vi t y, S e rvi ce, I ntent, View, But t on, App l i ca t i on,
Cont ent P rovider . .). (, maps awt )
,
.
, ,

<us e s - l ibrary>.



ndrid-
View () Vi ewG roup (
). view V i ewG roup
View (. 5 . 1 ) .
, v i ew.

. 5. 1 . G V i ew Vi ewGroup

View -
Android. View ,
,
, . .
View - ,
.
View , , ,
, ,
. , view
.
V i ewGroup ,
(layouts),
,
, , .

62

5 .1 .
Android
, V i e w V i ewG roup,
. 5 .2 . ,
-
.

View
View

View
View
View
View
View

. 5.2.

Adroid

.
, View Vi ewG roup
.

5.2 .
, , -
,
. n
, n .
:

XML. Adroid
L-, View
V i ewG roup;

Layout V i ew, ViewGroup


.

63

Adroid

. ,
XML, ,
, , ,
,
XML.
D- Ecl ipse -
Layout Ed itor (. 5 .3 ), ?\
,
res/\ayout/ .
Pfopertles

. 11 i

- IIJ TableROV\/Ql (iableRow)


( &.tton01 (Sutt ort)
J) utton02 (utt011 )
@ uttonO(utton)

([IDralerFrer
!I) ExpandableL.stV

[) Fr.nelayout
([]Gdlr'rew

(ii] Hootont:aiScro/1

ImaqeSwltchr

...

1!.) TableRow02 (To!!bleRow)


IT 1 TableRowO(TRow)

llJ eP:ow04 (aieRow)

: :: But.ton

Auto lrnk
BackQround
Buffertype

Cllck.,ie
Cursor v1srbl
Drae bottom
Dra1aeleft
Drawable paddrnq
Drawaie r'Qht

...

Drawaie top

Drawrng ache qualr


Dup/lcdte parent st<
Edtor extras

{jJLnearLo!Jyout

(G"j'<*.f!r.. . :".;:; ;;"f.:,.

ERJI)srze
Em<

Surfao:elr'tew

FadtngedQe
Fdlng e1ge length

2) V.ew

(!}VIewStu

Flts system wrndow

,,.i AnalogCiock
@ AutoComplete . . .

Focusable
Focusdie n touch r
Freezes text

@utton

Gravll:y

Haptrcfeedbackf'nc
HerQht
Hrnt

(Q Checkox

. 5.3. Layout Editor


- L- . X M L
, L- W- .
L-
,
, .

, ,

.

64

, L-
(portrait, landscape),
. , L-

, .
XML View ViewGroup (
). View - , ViewGroup -
(. . 5 .3 , Outline). View
Vi ewGroups Jv-, addView (View ) ,
View Vi ewGroup .
,

.
, Android (
), Linea rLayout, Re lat iveLayout, TaleLayout . (
).
, ,
.

5.2 . 1 . XM L
L- Android,
, ,
, W- HTML
.
,
View ViewGroup.
,
,
, .
,
. , L- " Hel lo,
Android ! " 3 ( 5 . 1 ).

< ?xrnl ve r s i on= " l . O " encoding= " u t f- 8 " ? >


<Linea rLayout xrnlns : andro id= " http : / / s chema s . android . com/ apk / re s /andro id"
android : or i ent ation= "ve r t i ca l "
android : l ayout_width= " f i l l_pa rent "
android : la yout_he i ght= " fi l l_parent " >

65


<TextView
andro id : id= " @ +id / TextViewO l "
android : layout width= " f i l l pa rent "
_
_
android : layout he i ght= " wrap content "
_
_
android : t ext=" @ s t ring / he l l o " >
< / TextView>
< / LinearLayout >

L- : - L
, View (
View - TextView) .
, Vi ew, L-,
.
, ,
.

5.2.2. L-
L- <Linea rLa yout >
View . TextView ( ),
. , , . 5 . 1 .

5. 1 .

L-

XML

xmlns : android

XML, Adroid, , Ad roid .

"http : / / s chema s . android . com/ apk / re s /android"

android : l ayout_width

,
V i ew ( Vi ewGroup) . - ,

, , f i l l_parent
android : l ayout_he i ght

android : l ayout_width,


android : t ext

, Textv iew.

. he l l o es/values/sti ng s.xm l .
n
n , n , n

66

view vi ewG roup


L-.
View ( , TextView t e x t S i z e ) ,
View,
.
V i ew, view (
id, layout_wi dth, layout_he ight ) .
, L- u
,
, - . ,
, )
Adroid, L-
, , L
.
, , <TextView> e x tV i ew
, <LinearLayout>
Linea rLayout . ,
Adroid ,
.
. 5 .2 : L- .

5. 2.

L-

X M L

Java

android : gravi t y

setGravi t y ( int )

android : hei ght

setHeight ( i nt )

android : t ext

setText ( CharSequence )

android : t extCo l o r

setTextCol or ( ColorStateLi st )

android : t ext S i z e

setextS i z e ( f l oat )

andro i d : width

setWidth ( i nt )

androi d : t extCo l o r H i g h l i ght

s e t H i ghl i ghtColor ( i nt )

View
,
. ,
,
L- id.
L- :
and roid : id= " @ + i d /TextViewO 1 " ,

67

@ ,
XML
.
+ , - ,
R.j ava, Adroid
, 5 .2.

pu l i c final class R
pul i c static final class id
pu i c static fina l int TextView01=0x7 f 0 5 0 0 0 0 ;


, ,

Re lat iveLayout ( ). Re lat iveLayout

, :
andro id : l ayout_toLe ftOf= " @ id/ TextVi ewO l "


. 5. 4. 4.

,
( ,
, ).

5 . 3 .

,
.
onC reate ( ) s e tContentView ( ) ,
:
R . layout . layout_fil e_name

, L- mai .xm l,
Act ivit y ( 5 .3).

68

@ Overr ide
pu i c vo id onCreate ( Bundle savedins tanceState )
super . onCreate ( savedins tance Stat e ) ;
setContentView ( R . layout . ma in ) ;

.
.
, ,
, - . .
.

5 .4.
,
:
r:J FrameLayout ;
r:J L inea rLayout ;
r:J Tae Layout;
r:J Re lati veLayout .

,
, View.

ViewGroup

(. 5 .4)

Framelayout
Relativelayout

-, -Ta-b-le-La_y_ou-t'l
. 5.4.

5.4. 1 . FrameLayout
FrameLayout .
, -

69

View viewGroup.
FrameLayout .
" ", Ecl ipse
New Android Project :

Project name -

FrameLayoutApp;

g Application name -

Frame Layout Sample;

Package name - com . samples . frame layout;

Create Activity - FrameLayoutAct ivity.

main.xml , 5 .4.
, Layout Editor, , L-,
.

<?xrnl ve r s i on= " l . O " encoding= " ut f- 8 " ? >


<FrameLayout xmlns : android= "http : / / schemas . android . com/apk/ res /android"
andro id : id= " @ + i d / FrameLayoutO l "
andro id : l ayout_he ight= "wrap_content "
android : l ayout_width= " t'i l l_pa rent " >
<Button android : text= " @ +id/But tonO l "
android : id= " @ + id/ButtonO l "
android : l ayout_width= "wrap_content "
android : l ayout_height= "wrap_content " / >
< / FrameLayout>

.
, . 5 . 5 .

Frame Layout

FrameLayout
View. View
',
, ,
FrameLayout
:
android : l ayout_width= " fi l l_pa rent "
android : l ayout_he i ght= " fi l l_pa rent "

70

. 5.5. Frame Layout

5.4.2. LinearLayout
L i n e a r L a yout n
n - ,
, n and r o i d : o r i e nt a t i o n :
and r o i d : o r ient a t i on= " ho r i zont a l "


a n dr o i d : o r i en t a t i o n = " v e rt i ca l "

n n ,
n n
, .
n n ,
n .
n n
New Android Proj ect :

Project name - L i n e a rLa yout ;

Application name - L i ne a r Layout

Package name -

Create Activity - L i n e a r L a yout

S amp l e ;

. s amp l e s . l i ne a r l ayou t ;

Act i v i t y .

71

res/layout/mai n .xml
, 5 . 5 .

Linea rLayout

< ?xml ve rs ion= " l . O " encoding= " ut f- 8 " ?>


<Linea rLayout xmlns : andro id= " http : / / scherna s . andro id . com/apk / re s / andro id"
android : id= " @ + id/Linea rLayout O l "
andro id : l ayout_width= " fi l l_pa rent "
andro id : layout_he ight= " fi l l_pa rent "
andro id : o rientat ion= " ho r i z onta l " >
<Button
andro id : id= " @ + id/buttonl "
android : l ayout_width= " wrap_content"
android : l ayout_he i ght= "wrap_cont ent "
andro id : text="ButtonO l " / >
<Button
android : id= " @ + id/button2 "
andro id : layout_width= "wrap_content "
android : l ayout_he ight= "wrap_cont ent "
android : text= " Button0 2 " />
<But ton
android : id= " @ + id/button "
android : layout_hei ght= "wrap_content "
andro id : layout_width= " fi l l_pa rent "
andro id : text=" ButtonO " / >
< / LinearLayout>

, andro id : l ayout_width
wrap_cont ent, - fi l l_parent, . .
.

. andro
id : layout_height:
andro id : o rientat ion= " vert ical ",

.
Linea rLayout
. 5 .6.
Linea rLayout andr <;> id : l ayout_we ight,
. -

72

n "" n n
, n n
. .

. 5.6. L i n e a r L a yout

, n,
t:, 1 , (0),
n , n
, . ,
, n.
n 2 ( 0), "
", , n 5 0% n
, 25% n.
n n Linea rLayout
" " n
New Android Proj ect :

Proj ect name -

Application name - T a e L a yout

Package name -

Create Activity - T e x t V i ewAct i v i t y .

Linea rLayoutWe i g h tApp;


S amp l e ;

. sampl e s . t a e l ayou t ;

73

res/layout/main .xml LinearLayout


Editext, 5 .6.

< ?xrnl ve rs ion= " l . O " encoding= " ut f- 8 " ?>


<Linea rLayout xrnlns : andro id= " http : 1 / schernas . android . com/apk / re s / andro id'
andro id : id= " @ + id/ Linea rLayout O l "
android : layout_width= " fi l l_pa rent "
android : layout_he i ght= " fi l l_pa rent "
android : orientation= "ho r i z onta l " >
<EditText
android : id= " @ + id/EditText O l "
android : layout_width= "wrap_content "
android : layout_he i ght= "wrap_content "
android : text= " EditText O l "
android : layout_we i ght= " O " / >
<EditText
android : id= " @ + id/EditText 0 2 "
android : layout_width= "wrap_cont ent "
andro id : layout_he ight= "wrap_content "
android : layout_we ight= " l "
android : text= " EditText 0 2 " / >
<EditText
android : id= " @ + id/EditText O "
android : layout_width= "wrap_content "
android : layout_he ight= "wrap_content "
android : layout_we ight= " 2 "
android : text= "Edi tText O " / >
< / LinearLayout>


. 5 .7 .

android : layout_we ight

, X M L
.
l ayout_we ight , ,
.

74

. 5.7. and r o i d : l a yout _we i ght

5.4.3. Ta/eLayout
ale Layout n
. al e L a yout ,
. a e Layout .
n
n .
n TaleRow,
TaleLayout ( Ta leRow n
).
, V i ew
V i ewG roup. V i e wG r oup (n,
n Tale Layout Linea rLayout ).
n New And roid Project
:
D

Proj ect name - T a l e L a you tApp;

Application name - T a l e L a yout

Package name - . s amp l e s . tal e l a yo u t ;

Create Activity - T a l e L a youtAc t ivi t y.

S amp l e ;

75

aleLayout
, .

Tal eRow

Tal eRow Properties :

Layout height - wrap_content;

Layout width -

Gravity - center.

f i l l_parent;

g ravity ,
- .
Properties :

Layout height - wrap_content;

Layout width - 2 0pt.

, ( 1 , 2, 3, 4, 5, 6,
7, 8, 9, * , , # ) .
, . 5 . 8 .

. .............. ......... ..................EJ


,... ,i '
=

);>

+ - ' t

aieLvutoi <elayut)
;:. [) TaieRowO I (TaieRow)

...

Button O I (Button)
Button02 (Button)
ButtonO (Button)

[) TaieRow02 (TaieRow)
Button04 (Button)
Button05 (Button)
ButtonO (Button)
[) TaieRowO (TaieRow)
Button07 (Button)

Button08 (Button)

Button09 (Button)
[) TaieRow04 (TaieRow)
Button ! O (Button)
Button l l (Button)
Button 1 2 (Button)
. 5.8. TaleLayout

, 5 . 7 .

< ?xml ve r s i on= " l . O " encoding= " u t f- 8 " ?>


<TableLayout xmlns : androi d= "http : / / s chemas . android . com/apk/ res /android "
andro id : id= " @ + i d/TableLayout O l "

76

5
android : layout_width= " f i l l_pa rent "
android : layout_he ight= " fi l l_parent " >
<Tal eRow
android : id= " @ + id/TaleRowO l "
android : layout_he ight= "wrap_content "
android : layout_width= " fi l l_pa rent "
android : gravity= " cent e r " >
<Button
androi d : i d= " @ +id/ButtonO l "
android : l ayout_he i ght="wrap_content "
androi d : text= " l "
android : l ayout_width= " 2 0pt " / >
<Button
android : id= " @ +id/Button0 2 "
android : layout_he ight= "wrap_content "
androi d : text= " 2 "
androi d : layout_width= " 2 0pt " / >
<Button
androi d : i d= " @ + i d/ButtonO "
android : l ayout_he ight=" wrap_content "
androi d : text= " "
androi d : l ayout_width= " 2 0pt " / >
< /TaleRow>
<Tal eRow
android : id= " @ + id/TaleRow0 2 "
androi d : l ayout_he i ght= "w rap_content "
androi d : l ayout_width= " fi l l_parent "
androi d : gravi ty= " cente r " >
<But ton
android : id= " @ + id/Button0 4 "
androi d : l ayout_he i ght = "wrap_content "
android : l ayout_width= " 2 0pt "
android : text= " 4 " / >
<Button
android : id= " @ + i d/Button0 5 "
android : l ayout_he ight=" wrap_content "
android : l ayout_width= " 2 0pt "
androi d : text= " S " / >
<But ton
androi d : i d= " @ + i d/Button0 6 "
android : l ayout_he i ght=" wrap_content "
android : l ayout_width= " 2 0pt "
android : text= " " / >
< /Tal eRow>


<Tal eRow
android : id= " @ + id/TaleRowO "
android : layout_he ight="wrap_content "
android : layout_width= " fi l l_parent "
android : gravi ty= " cent e r " >
<Button
android : id= " @ + i d/Button0 7 "
android : layout_he ight="wrap_content "
android : layout_width= " 2 0pt "
android : text= " 7 " / >
<Button

android : id=" @ + id/ButtonO B , ;


android : layout_he ight= "wrap_content "
android : layout_width= ".2 0pt "
android : text= " B " / >

<Button
android : id= " @ +id/Button 0 9 "
android : l ayout_he i ght="wrap_content "
android : l ayout_width= " 2 0pt "
android : text= " 9 " / >
< /TaleRow>
<Tal eRow
android : id= " @ + id/TaleRow0 4 "
android : l ayout_he ight= "wrap_content "
android : l ayout_width= " fi l l_parent "
android : gravi ty= " cente r "
<Button
android : id= " @ +id/But ton l O "
android : l ayout_he ight= "wrap_content "
android : l ayout_width= " 2 0pt "
android : t ext= " * " / >
<Button
android : id= " @ + id/Buttonl l "
android : l ayout_he ight=" wrap_content "
android : l ayout_width= " 2 0pt "
android : text= " O " / >
<Button
android : id= " @ + id/Button l 2 "
android : l ayout_he i ght="wrap_content "
android : l ayout_width= " 2 0pt "
android : text= " # " / >
< /TaleRow>
</Tal eLayout>

77

78

.
Ta l e Layout ,
. 5 .9 .

. 5.9. Tab l e Layout

5.4.4. RelativeLayout
( )

( ).

Re l a t i veLa yout

Re l a t ive Layout ,
, ,
, .
, L-, ,

, , ,
.
New Android Proj ect
:
D

Proj ect name - Re l a t iveLayoutApp;

Application name - Re l a t i ve Layout

S amp l e ;

79

Package name - . sample s . relat ivel ayout ;

C reate Activity - RelativeLayoutAct ivity.

5 . 8 .

< ? xml ve r s i on= " l . O " encoding= "ut f- 8 " ?>


<Relat iveLayout
xmlns : andro id= "http : / / s chemas . android . com/ apk / res /android"
andro id : layout_he ight= " fi l l_parent "
andro id : l ayout_width= " f i l l_pa rent " >
<Button
android : id= " @ + id/button cente r "
android : text= " Cent e.r "
android : l ayout_width= "wrap_content "
android : l ayout_he ight= "wrap_conten t "
android : layout_centerVertical= " t rue "
android : layout_centerinParent= " t rue " / >
<Button
android : id= " @ + i d/button_bottom"
android : layout_width= " wrap_content "
android : l ayout_he i ght="wrap_content "
androi d : text= " Bottom"
android : layout_centerHori zontal= " t rue "
android : layout_al ignParentBottom= " t rue " />
<But ton
android : id= " @ + id/button_top "
android : layout_width= "wrap_content "
android : l ayout_he ight= "wrap_content "
android : text= " Top"
android : layout_a l i gnPa rentTop= " t rue "
android : l ayout_centerHori zontal= " t rue " />
<Button
android : id= " @ + id/button left "
android : layout_width= "wrap_content "
android : l ayout_he ight="wrap_content "
android : text= " Le ft "
android : l ayout_a l i gnParentLeft = " t rue "
android : l ayout_centerVertical= " t rue " / >
<Button
android : id= " @ +id/button_r ight "
android : l ayout_width= "wrap_content "
android : layout_he ight= "wrap_cont ent "

5
android : text=" Right "
androi d : l ayout_a l i gnPa rentRight = " t rue "
android : l ayout_centerVert i ca l = " t rue " / >
<But ton
andro id : id= " @ + id/button_re l right "
android : layout_width= " wrap_content "
android : l ayout_he i ght= "wrap_conten t "
android : layout_toLe ftOf= " @ id/button_right "
android : l ayout_a l i gnTop= " @ id/button_right "
android : text= "RelRight " / >
<Button
android : id= " @ + id/button rel left "
andro id : l ayout_width= "wrap_content "
andro i d : layout_he i ght= "wrap_content "
android : l ayout_toRightOf= " @ id/button_left "
android : l ayout_a l i gnTop= " @ id/button_l e f t "
android : text= "Re l Le ft " / >

< /Re lativeLayout>

0
,
( , layout_toLe ftOf ) ,

@ id/ id.

. 5. 1 0 . Re l a t i veLayout

81

.
Re lat i veLayout , . 5 . 1 .

5 . 5 .
H i era rchy Viewe r
Android S DK Hierarchy Viewer -
(. 5 . 1 1 ) .

.
Hierarcl1y V iewer

- Pixel Perfect V iew.

F ifo V lew

re;hv

Ser'Ver

stop Server R.efesh s

!..d 'Jew H&rchy DISJ)I&yYew lnvat:e Request liiiVO\.t

. . . . . . .......... ..... .. ....... . . . ,- ....

:-:: : :.:::-::-:i-:r -:: --r .L<!!uncher


:---- . . '-*-S"'I_ anr-:1
:_s_l :.
liiN-L-yttt
j-?-...-- ---:.
;TrklnQVI
j::: ::: : : ..
statusill r

tiY'9UNd-l

. . . ..

20%

. 5 . 1 1 . H i e ra rchy Viewe r

Hierarchy Viewer :
D

hierarchyviewer. bat tools/ Adro i d SDK.


drid- .
. < Focused
11'/indow> ,
, -

82

, Layout View H ierarcl1y


Viewer;

Load View Hierarchy.


Layout View.
Pixel Perfect View,
Layout View.

Refresh
Windows , .

5 . 5. 1 . Layout View
Layout View .
:

Tree View - ;

Properties View - ;

Wire-frame View - .

Fkl V11J1N ll!fNC

Setv'

............. ----
----'ile!WiietW'Iy \1

'"''" ]

--

::---'
:dl
l

Ydoto Rst\Ayout

ritJa.l

' od.t.ll'\111\ _ .. "

od.'\Uiqoo_'ll !

. 5.1 2. Layout View Hierarchy Viewer

. 5 . 1 2 Layout View
RelativeLayoutApp . 5. 5. 4.

83

, Properties View
Tree View.
Wire-frame View
.
.
Layout View
- Invalidate Req uest Layout.
inva l idate ( ) reques tLayout ( )
.

, Layout Vi ew
. Layout Vi ew , Load
View H iera rchy .

5.5.2. Pixel Perfect View


Pixel Perfect View
. :

Explorer View - ;

Normal View - ;

Loupe View - n .


, (padding) (margin).
-
. n
n ,
(paddi g). n
n
(margi ).
n
n Normal
Views Loupe Views. n,
n, n
. n Load
n Normal Views, n .
nn .

84


.
-- - -'.<; .. .;.

stop Ser.oer Rehesh Wt"ldow$ I.V!eW i'lord'>)l DlsployVItw

ltd:e RaQUOstLayout

Llnearlayoul:
U Fra!:L.syout

Yextvtew

J Fr4tl'lel-wcut
: ";..,) Relatvelayct
uttcn
ul.tCil
Butta'l
utton
ul.ta'l
vt.tm
Elul.ta'l

. 5. 1 3. Pixel Perfect View Hiera rchy Viewe r


Normal View Loupe Vi ews
(5 ) ,
Expl orer View .
Explorer View, Load
Vi ew H iera rc h y .

- V i ew,
. , -
. Adroid v.,
, ,
.

6 . 1 .
Adroid :

T e x t V i ew;

Edi t T e x t .

e x t v i ew
. ,
E d i t T ex t .
TextView E d i t T e x t ,
V i ew, .
. 6 . 1 .

TextView
Editext

. 6.1 .

86

6 . 1 . 1 . TextView
Textview -
. extView n
n .
n . ,
TextView n
-n .
, ,
.

android : text, :

TextView

andro i d : text= " He l l o , Android ! "

setText ( ) :

TextView text
11

( TextView ) f indVi ewByid ( R . id . text ) ;

text . setText ( " He l l o , Android ! " ) ;


, L

XML-pecypc:
android : text= " @ s t r ing /text_he l l o " ,

text_he l l o -

XML-pecypc s etText ( ) ,
,
R.j ava ( ), :
TextView text
1/

( TextView ) f indViewByid ( R . id . text ) ;

text . setText ( R . s t r ing . text_he l l o ) ;

extView L-
. , L-,
TextView:
D

android : text Si z e - .
:

(pixel s) - ;

87

dp (density-i ndependent p ixels) - .


,
;
sp (scale-independent p i xels) -
;

i n (i nches) - , ;

pt (points) - 1 /72 , ;

m m ( m i l l imeters) - ,
.


sp, , :
android : text Si ze= " 4 B s p " ;

android : text Style

norma l ;

bold;

italic.

. :

android : t extS tyle= "bo l ct " ;

.
:

androi d : textColor -

#RGB;

#ARGB;

#RRGGBB;

#AARRGGBB;

R, G,
,
(alpl-channel).
, , 1 00%.
, alpha, - .
-

TextView '
.
TextView
Create New Project :

Proj ect name - TextView;

Application name - TextView

Sample;

88

Package name - . samples . textview;

Create Activity - TextViewActivi t y.

Linea rLayout
TextView text l , text 2 , text; text 4 . textl
L-:
android : text= " He l l o , Android ! "

text2 .
,
text text 4 . 6 . 1 .

< ? xml ve r s i on= " l . O " encoding= " ut f-8 " ? >
<Linea rLayout xmlns : android=" http : / / schemas . android . com/apk / re s / android"
android : id= " @ + id/Linea rLayout O l "
android : layout_width= " fi l l_pa rent "
android : layout_he ight= " fi l l_parent "
andro id : orientation= "vert i ca l " >
<TextView
android : id= " @ +id/text l "
android : l ayout_width= "wrap_content "
android : layout_he ight = "wrap_content "
android : text= "Hel l o , Android ! " />
<TextView
android : id= " @ +id/text 2 "
android : la yout_width= "wrap_content "
android : layout_he i ght = " wrap_content "
android : text= " @ s t ring / text_hel l o "
android : text S t yle= "bold" />
<TextView
androi d : id= " @ +id/text "
androi d : layout_width= "wrap_content "
android : la yout_height="wrap_content "
android : textS i z e= " sp"
android : textS t yle= "bold"
android : textColor= " #AAA " / >
<TextView
android : id= " @ +id/ t ext 4 "
android : layout_width= "wrap_content "
android : layout_he ight= "wrap_content "

89


android : text S i z e= " 4 8sp"
android : textS t yle= " i t a l i c " / >
</Linea rLayout>

stri ngs.xm l
"Hel lo, Android ! " ( 6 .2).

_n

< ? xml ve rs ion= " l . O " encoding= "utf-8 " ?>


<resources>
< s t ring name = " app_name " >TextView Sample < / s t ring>
< s t ring name= " text_he l l o " >Hel l o , Android ! < / s t ring>
< / resources>

TextViewActi vi t y tVi w text , text 4


s etext ( ) .
6.3 .
-

package corn . samples . textview ;


irnport android . app . Activi t y ;
irnport android . os . Bundle ;
irnport android . widget . TextView ;
pu l i c class TextViewActivity extends Act ivity {
@ Ove rride
pul i c void onCreate ( Bundle s aved!ns tanceState )
supe r . onCreate ( savedinstanceStat e ) ;
setContentView ( R . layout . rnai n ) ;
1 1
final TextView text
( T extVi ew ) findVi ewBy!d ( R . id . text ) ;
1 1

text . s etText ( "He l l o , Android ! " ) ;


final TextView text 4

( TextView ) fi ndViewBy! d ( R . i d . text 4 ) ;

1 1

text 4 . setText ( R . s t r ing . text_hel l o ) ;

90

. 6.2. TextView

. ,
. 6 . 2 . ,
- , - ,
- .

6 . 1 . 2 . EditText

Edi t e x t -
.
TextVi ew,
.
EditText

Edi t T e x t - g e t T e x t ( ) , ,
E d i t T ex t .
E d i t a l e . ,
(
S t r i ng, ,
s t r i ng ) .
:
D
D

s e l ectAl l

( ) - ;

s e t Se l e c t ion ( i n t

s t a rt ,

int

s top )

s t a r t s t op;

s e t S e l e c t ion ( i n t i ndex ) -

index.

91


extView.
setType face ( nul l , Type face ) , s etTextS i z e ( int text S i z e ) , SetTextColor ( int
Color ) .

Create New Project


:

Proj ect name - Edi tTextApp;

Application name - EditText

Package name - . samples . scroll view;

C reate Activity - Edi tTextActivity.

Sample;

6.4.

H e l l o, Android!

. 6. 3 . Edi tText

<?xml ve r s i on= " l . O " encoding= " ut f- 8 " ? >


<Linea rLayout xmlns : android= " http : / / schemas . android . com/ apk / re s / android"
android : or i enta t i on= "ve r t i ca l "
android : layout_width= " fi l l_parent "
android : la yout_he ight= " fi l l_pa rent " >

92
<Edi tText
androi d : id= " @ + id/EditText O l "
android : la yout_he ight= " f i l l_pa rent "
android : la yout_width= " fi l l:_parent "
android : text= " He l l o , Android ! " />
< / LinearLayout>

.
extview . 6.3 .

Act i vi ty.

.

6 . 2 .
TextView
,
TextView (
, )
.

Android
scrol lView
Hor i z ont a l Scrol lView,
vi ewGroup, . 6.4.

View
ViewGroup
ScroiiView
HorizontaiScroiiView
. 6.4.

S c rol lView Hor i z onta l Scrol lView

Hor i z ont a l S c ro l lView -


FrameLayout, ,
. , ,
.
LinearLayout
.
Scro l l View

93

scrol lView, ,
,
scrol lView
Hor i z ont a l S c rol lView. Scrol lView
, Hor i z ont a l S c ro l l View - .
. Ecl ipse
Create New Project :

Project name - Scroll sApp;

Application name - S c rol l s

Package name - com . samples . s crol l s ;

Create Activity - Scro l l sAct ivity.

Sample;

main.xml ,
S c ro l lView, Hori zont a l S crol lView TextView, 6 . 5 .

< S c rol lView xmlns : android= "http : / / schemas . android . com/apk/res/android"


android : id= " @ +id/scro l l "
android : layout_width= " wrap_content "
android : layout_he i ght= "wrap_content " >
<Ho r i zontal Scrol lView
android : id= " @ +id/scrol l_hor "
androi d : layout_width= " fi l l_parent "
android : layout_he ight= " f i l l_parent " >
<TextView
android : id= " @ + id/ t extview"
android : layout_width= "wrap_content "
android : layout_he ight="wrap_content "
android : textColor= " # O O O O O O "
android : background= " # FFFFFF"
android : text S i z e= " 2 4 px "
android : shadowDx= " O "
android : shadowDy= " O "
android : shadowRadius= " O "
android : shadowCol o r= " # FFFFFF"
android : i s Scrol lCont a ine r= " t rue " / >
< /Hori zonta l S c rol lView>
< / Scrol lView>

94

S c ro l l ViewActi vi ty oncre a t e ( )
TextVi ew, L-,
s etText ( ) ,
.
S c r o l l Vi ewAct i vi ty 6.6.



,



u-

. 6. 5.

package com . sampl e s . s c ro l l s ;


import androi d . app . Ac t ivi t y ;
import androi d . o s . Bundle ;
import androi d . widget . TextView ;
pu l i c c l a s s S c ro l l sAct i v i t y ext ends Act iv i t y
@ Ove rride
pu l i c void onC reate ( Bund l e s avedins tance S t a t e )
s upe r . onC reat e ( s avedins tance S t a t e ) ;
s e t Cont entView ( R . l a yout . ma in ) ;

95

TextView text

( TextView ) findViewByid ( R . id . textview ) ;

1 1

text . setText ( "

.
extview . 6.5 .

6 . 3 .
Imageview.

, ImageView

, .
extView,

Imageview ,
- .
:
D set imageResource ( i nt res i d )

;
D set imageURI ( Uri uri )

- URI ;

D set imageBi tmap ( B i tmap itmap ) -

L-
andro id : s rc .

,
getMinimunWidth ( ) ,

setScaleType ( ) .

ImageView


, setMaxWidth ( ) , getMinimunHei ght ( ) ,
- get Scal eType ( ) ,

setMaxHe ight ( )

ImageView
Create New Proj ect :
D

Proj ect name -

Application name -

Package name - com . s ampl es . imageview;

C reate Activity -

ImageVi ewApp;
ImageView Sample;

ImageVi ewAct ivity.

res/drawa\e/ , android.png
adroidmarker.png ( CD-ROM).

96

,
ImageView image l , image 2 . .
android : s rc= " @ drawale / andro id" .

6. 7 .

< ? xml ve r s ion= " l . O " encoding= "utf- 8 " ? >


<Linea rLayout nlns : android= " http : / / s chema s . android . com / apk / res / andro id"
android : layout width= " f i l l pa rent "
_
_
andro id : layout he i ght= " fi l l_p arent "
_
android : gravity= " cent e r "
andro id : or i entation= " hori zontal " >
< ImageView
android : id= " @ + id / image l "
android : layout width= " wrap content "
_
_
android : layout he i ght= "wrap content "
_
_
android : s rc=" @ drawale / andro id"
android : padding= " l Opx " / >
< ImageView
android : id= " @ + id / image 2 "
android : layout width= " wrap content "
_
_
android : layout he i ght= "wrap content "
_
_
android : padding= " l Opx " / >
< / Linea rLayout>

ImageViewAc t ivity
ImageVi ew, s e t imageResource ( ) , 6 . 8 .

package com . sample s . imageview ;


import android . app . Act ivi t y ;
import android . os . Bundle ;
import android . widget . ImageView;
pu l i c class ImageVi ewActivity extends Act ivity {
@ Ove rride

97


pu l i c vo id onCreate ( Bundle savedins tance State )
supe r . onCreate ( savedinstanceState ) ;
setContentView ( R . layout . mai n ) ;
final ImageView image

( ImageView ) findViewByid ( R . i d . image2 ) ;

/ 1

image . se t imageResource ( R . drawale . andro idmarke r ) ;

. ,
. 6.6.

. 6.6 .

ImageView .

6 . 4 .
,
, , , .
, ,

.
View ,
on . . . Listener ( ) , -

98

.
. Android, Vi ew,
,
.
view :

OnC l i c kL i s tene r ;

OnLongCl i c k L i s tener;

OnFocusChangeL i s tener;

OnKeyL i s tene r;

OnTouchL i s tene r ;

OnC reateContextMenuLi s tene r.

, ,
,
OnC l i ckLi s t ene r onC l i c k ( ) ,
,
setOnC l i c kL i s tene r ( ) :
but ton l . s etOnC l i ckLi s t ene r ( new V i ew . OnC l i c kL i s tene r ( )
pu l i c vo i d onC l i c k ( V i ew v )
mText . s etText ( " C l i c k on Fi r s t Button" ) ;

,
.

6 . 5 .
Android :

Button;

Che c kBox;

Toggl eBut ton;

Radi oBut ton;

ImageButton.



. Imageutt on,

Textvi ew,

99

ImageView

utton Textview.
CompoundButton.
CompoundBut t on
: Che c kBox, Toggl eButton
Radi out ton. . 6.7.
Object

-----,

View

-----,

TextView

,.--------,
Button

,---------,
'-------1 Com pou ndButton

l mageView

ToggleButton
-----,

'-------1 l mageButton

1
J
1

-------,
CheckBox

RadioB utton

. 6.7.
Button, Chec kBox, Toggl eButton, RadioButton ImageBut ton

Compoundutton
- checked unchec ked.
. compoundutton
onche c kedChangeListener
onChec kedChanged ( ) .

6.5. 1 . Button
utton -
.
onC l i c k .
onc l i c k ( ) .
, , .
Ecl i pse C reate New Project
:
D

Proj ect name - utt onApp;

Application name - Button

Package name -

C reate Activity - ButtonAc t i v i t y .

Samp l e ;

s amp l e s . but ton;

100

LinearLayout
buttonl button2 , " Button 1 " " Button 2"
( 6.9).

< ? xml ve r s i on= " l . O " encoding= " ut f - 8 " ? >


<Linea rLayout xmlns : andro id= " http : / / s chemas . android . com/ apk / res / andro i d "
android : or i enta t i on= "ve rt i ca l "
android : layout width= " f i l l__;p a rent "
_
andro id : layout he i ght= " fi l l parent " >
_
_
<But ton
android : id= " @ +id / buttonl "
android : layout width= " wrap content "
_
_
android : l ayout height= " wrap content "
_
_
android : text= " Button 1 " / >
<Button
android : id=" @ +id / button2 "
android : layout width= "wrap content "
_
_
android : layout he ight= "wrap content "
_
_
android : text= " Button 2 " / >
<TextView
android : id= " @ +id / text "
android : layout width= "wrap content "
_
_
android : layout hei ght= "wrap content " / >
_
_
< / LinearLayout>

uttonActivity ,
6. 1 .

package com . s ample s . button 2 ;


import android . app . Ac t ivit y ;
import android . os . Bundle ;
import android . widget . Button ;
import andro id . widget . TextView;
import android . view . View ;
pu l i c c l a s s ButtonActivity extends Act ivity {
private TextView mText ;

101

@ Ove r ride
pu l i c voi d oC reate ( Budle s avedistace State )
supe r . oCreate ( s avedistace State ) ;
s e tCotetView ( R . layout . ma i ) ;
mText

( T extView ) fidViewByid ( R . id . text ) ;

fial Butto buttol

( Butto )

fidViewByi d ( R . id . buttol ) ;

but tol . s e tOC l i ckListee r ( ew View . OC l i c kL i s tee r ( )

pu l i c vo id oCl i c k ( Vi ew v )
mText . s etText ( " C l i c k Fi rst But to" ) ;

fial Butto butto 2

( Butto )

fidViewByi d ( R . id . butto 2 ) ;

but to 2 . s etOC l i c kL i s tee r ( ew View . OCl ickLis tee r ( )

pu l i c vo id oC l i c k (View v )
mText . s etText ( " C l i c k Secod But t o " ) ;

.

(. 6 . 8).
.
ocreate ( ) .

, ,
oCreate ( ) .
s e toc l i c k L i s teer ( )
, :
butto . s e tOCl i c kL i s tee r ( butto c l i c k ) ;
_

:
pu l i c OCl i c k L i s tee r but to c l i c k
_
@ Ove r ride

w OC l i ckListee r ( )

pu l i c void oC l i c k (View v )
1 1

1 02

. 6.8.

ut tonAc t i v i t y , 6 . 1 1 ,
. ,
.

@ Ove r r i de
pu l i c vo id onC reat e ( Bundle s ave dins tance S t a t e )
buttonl . s e tOnC l i c kL i s tene r ( buttonl c l i c k ) ;
button2 . setOnC l i c kL i s t ene r ( button2_c l i c k ) ;

pu l i c OnCl i c k L i s tener but tonl_c l i c k

new OnC l ic k Li ste ne r ( )

@ Ove r r i de
pul i c void onC l i c k ( View v )
mText . s e tText ( " C l i c k on but tonO l " ) ;

pul i c OnCl i ckLis tener butt on2 c l i c k


@ Ove r r ide

new OnCl i c kL i s t ene r ( )

1 03


pub l i c vo i d onC l i c k ( V i ew v )
mText . s etText ( " C l i c k o n but ton 0 2 " ) ;

, , , , -

.
View . OnC l i c kL i s tene r:
pu l i c c l a s s Edi tTextAct ivity ext ends Act i v i t y
impl ements OnC l i c kL i s t ene r

:
abs t ract vo i d onC l i c k ( View v ) ,

uttonAc t iv i t y .
(, ),
s w i t ch, I D
get r d ( ) :
@ Ove r r ide
pu l i c vo i d onC l i c k ( V i ew v )
switch

( v . get i d ( ) )

/ 1 ID



. C reate New Project
:

Proj ect name - EditTextApp;

Application name -

Package name - com . s amp l e s . e d i ttext;

Create Activity - AutoCompl eteTextViewActivity.

Edi text S amp l e ;

, 6. 1 2 .

< ?xml ve rs ion= " l . O " encoding= " ut f - 8 " ? >


<TableLa yout xmlns : android= "h t tp : / / s chema s . androi d . com/apk/ res / andro i d "

1 04

android : l ayout_width= " f i l l_pa rent "


andro id : l ayout_hei ght= " f i l l_pa rent " >
<Tal eRow
andro i d : l a yout_width= " wrap_content "
androi d : layout_he i ght = " w rap_content "
android : g ravi ty= " cente r " >
<But ton
android : i d= " @ + id/button r "
android : l ayout_wi dth= " 5 0dp "
android : l ayout_he i ght= " wrap_content "
android : t ext= " R " / >
<But ton
andro i d : id= " @ + i d/button "
andro i d : layout_width= " 5 0dp "
android : l ayout_he i ght= "wrap_conten t "
androi d : text= " B " / >
<But ton
android : id= " @ + i d/button i "
android : l ayout_wi dth= " 5 0 dp "
android : l ayout_he i ght= "wrap_content "
andro i d : t ext= " I " / >
<TextView
andro i d : id= " @ + i d / l abe l "
andro i d : l ayout_he i ght= " w rap_content "
andro i d : text= " Text S i z e "
andro i d : paddingLe f t= " l Opx "
android : l ayout_width= "wrap_content " / >
<But ton
and roid : i d= " @ + i d/button_plus "
andro i d : l ayout_width= " 5 0 dp "
android : l ayout_he i ght= " w rap_content "
andro i d : text= " + " / >
<But ton
android : i d= " @ + id/button rninus "
android : l ayout_width= " 5 0 dp "
androi d : l ayout_he ight= "wrap_content "
and roid : text= " - " / >
< /TaleRow>
<Edi tText
android : id= " @ +id/edit text "
android : layout_he i ght= " fi l l_parent "

1 05


android : l ayout_width= " f i l l_parent "
android : text= " He l l o , Androi d " />
< / Ta leLayout>

Editext
( 6 . 1 3).

pa ckage com . samp le s . edittext ;


import android . app . Ac t iv i t y ;
import andro i d . g raphi c s . Typeface ;
import android . os . Bundl e ;
import andro id . view . View;
import andro id . view . View . OnC l i ckLis tene r ;
import android . widget . But ton ;
import android . widget . EditText ;
pu l i c c l a s s Edi tTextActivity ext ends Act ivity
impl ements OnC l ic k L i s t ene r
p r ivate float mText S i z e

20;

pr ivate EditText mEdit ;


@ Ove r r ide
pul i c void onC reate ( Bundl e s avedins tanceS tate )

{
s upe r . onCreate ( s avedinstanceState ) ;
s e t ContentView ( R . l a yout . ma in ) ;
mEdi t = { Edi tText ) f indV iewByid ( R . i d . edit_text ) ;
final Button buttonR
( Button ) f indVi ewByid ( R . i d . button_r ) ;
f inal Button buttonB
( Button ) f i ndViewByid ( R . i d . butt on_b ) ;
final Button buttoni
( Button ) f i ndVi ewByid ( R . i d . butt on_i ) ;
f ina l Button buttonPlus
( Button ) findV iewBy id ( R . i d . button_plus ) ;
f ina l Button buttoninus
( Button ) f i ndVi ewByid ( R . id . button_minus ) ;

1 06


but t onR . s etOnC l ickLi s t ene r ( thi s ) ;
but tonB . s etOnC l i c k L i s tene r ( thi s ) ;
but t on i . s e tOnC l i c k L i s t e ne r ( th i s ) ;
but tonPlus . s etOnC l i c kLi s t ene r ( th i s ) ;
but t oninu s . setOnC l i c kLi s tene r ( th i s ) ;

@ Ove r r i de
pu i c void onC l i c k ( V i ew v )
s w i t ch

( v . get i d ( ) )

c a s e R . i d . bu t t on r :
mEdi t . s e tType face ( nul l ,

Type face . NORAL ) ;

bre a k ;
c a s e R . i d . button :
mEdi t . s etType face ( nu l l ,

Type face . BOLD ) ;

brea k ;
c a s e R . i d . button i :
mEdit . setType fa ce ( nu l l ,

Typeface . I TAL I C ) ;

brea k ;
case R . id . bu t t on_plus :
if

( mText S i ze <= 7 2 )
mText S i ze+=2 ;

mEdit . s etText S i ze ( mTextS i z e ) ;


brea k ;
case R . i d . but t on minus :
if

( mText S i z e >= 2 0 )
mText S i z e -=2 ;

mEdi t . setText S i z e ( mText S i z e ) ;


brea k ;

.
,
(. 6.9).

6.5.2. RadioButton RadioGroup


Radi out t on ()
- Radi oGroup.
.
Radi oBut ton ,

107

He/lo, Android!

. 6.9.

. , , Red,
Green Blue, Red, Blue,
Red .
- t o g g l e ( ) ,
. ,
, i s Chec ked ( ) , ,
s e tchecked ( ) , .

Create New Proj ect :
D

Project n - Radi oButtonApp;

Application n - RadioButton

Package n - com . s arnp l e s . radiobutton;

Create Activity - Radi oBut tonAc t i v i t y .

S arnp l e ;


RadioG roup, TextView.
ID rad i o l , radi o 2 , radio Mode # 1 , Mode # 2 , Mode # 3 ,
6. 1 4 .

1 08

< ? xml ve r s i on= " 1 . 0 " encoding= " ut f- 8 " ? >


<RadioGroup xrn1ns : android= "http : / / s chema s . android . com/ apk / r e s / android"
andro i d : o r i enta t ion= " ve r t i ca l "
andro id : l a yout_width= " f i l l_pa rent "
andro id : l a yout_he i ght= " fi l l_parent " >
<Radi oButton
android : id= " @ + id/ radio 1 "
android : layout_width= " wrap_content "
android : layout_he i ght= "wrap_content "
android : text= "Mode # 1 "
androi d : checked= " true " / >
<RadioButton
android : id= " @ + id/ radio2 "
android : la yout_width= " wrap_content "
android : l a yout_he i ght= "wrap_content "
android : text= "Mode # 2 " / >
<Radi oButton
androi d : id= " @ + id/ radio "
android : l ayout_wi dth="wrap_content "
android : l a yout_he i ght= "wrap_content "
android : text= "Mode # 3 " / >
<TextView
androi d : i d= " @ + id/ text "
android : layout_width= " wrap_content "
andro i d : layout_he i ght= "wrap_cont ent "
android : text= " S elect : Mode # 1 " / >
< / RadioG roup>

onC l i c k ( )
. Radi outtonActivity
6. 1 5 .

pac kage com . samp le s . radiobutton ;


import android . app . Act ivi t y ;
import android . o s . Bundle ;
import andro id . view . View;

1 09

import android . view . View . OnC l i c k L i s t ene r ;


import andro id . widget . RadioBut ton ;
import android . widget . TextView ;
pu l i c c l a s s RadioBut tonDemo extends Act ivity
pr ivate TextView mText ;
@ Ove r r ide
pu l i c void onC reate ( Bundle s avedins tance State )
supe r . onCreate ( savedinstance State ) ;
setContentView ( R . layout . ma i n ) ;
final RadioButton radiol
( Rad ioBut ton ) f i ndViewBy id ( R . id . radiol ) ;
final Radi oButton radio2
( RadioBut ton ) f indViewByi d ( R . id . radio 2 ) ;
final Radi oButton radio
( RadioButton ) f indViewBy i d ( R . id . radio ) ;
mText

( TextView ) f indVi ewBy id ( R . id . text ) ;

radiol . s etOnC l i c kL i s tene r ( radi oBut ton C l i c k ) ;


_
radio 2 . s etOnC l i c kL i s tene r ( radi oButton C l i c k ) ;
_
radio . setOnC l i c kLi stene r ( radioBut ton C l i c k ) ;

OnC l i ckLis tene r radioButton C l i c k


pu l i c v o i d onCl i c k (View v )
RadioButton rb

new OnCl i c kL i s tener ( )

( RadioButton ) v ;

mText . s etText ( " S elect :

+ rb . getext ( ) ) ;

.
extVi ew,

radioBut ton_C l i c k. . 6 . 1 .

6.5.3. CheckBox
Chec kBox () - .

CompoundButton . OnChec kedChangeL i s t ene r .

1 10

. 6 . 1 0 . Radi oBut ton

che ckBox
C reate New Proj ect :
D

Proj ect name - Che c kox;

Application name - Chec kBox

Package name - com . s arnp l e s . chec kox;

C reate Activity - Chec kBox

Sarnp l e ;

Act ivity.


Chec kBox 6 . 1 6 .

< ? xml ve r s i on= "

. 0 " encoding= " ut f- 8 " ? >

<Linea rLayout xmlns : andro i d= " http : / / s chema s . andro i d . com/ apk / re s / andro i d "
android : id= " @ + id / L inea rLayout O l "
andro i d : l ayout_width= " f i l l_pa rent "
andro i d : l a yout_he i ght= " f i l l_pa rent " >
<Che c kBox
android : id= " @ + id/ checkbo x "
android : la yout_wi dth= "wrap_content "

111


android : la yout he i ght= " wrap content "
_
android : text= " Chec kBox OFF" / >
< / LinearLayout >

CheckBoxAct ivity
( 6. 1 7).

pa c kage com . s amp l e s . checkox ;


impo rt android . app . Act ivity ;
import android . os . Bundle ;
import android . widget . Chec kBox ;
import andro id . widget . Compoundutton ;
pu l i c c l a s s CheckBoxActivity ext ends Act ivity
implements Compoundut ton . OnChec kedChangeL i s tener
pr ivate Che c kox mChec kBox ;
@ Ove r r i de
pul i c void onCreate ( Bundle savedins tance S tate )
supe r . onCreate ( s avedins tance State ) ;
set Cont entView ( R . layout . ma i n ) ;
mCheckBox

( Chec kBox ) f indVi ewByi d ( R . i d . chec kbox ) ;

1 1
mChe ckBox . s etOnChec kedChangeLi s tene r ( thi s ) ;


pul i c void onChe c kedChanged (
Compoundut ton but tonView , bool ean i s Chec ked )
if

( i s Che c ked )
mChec kBox . s etText ( " Chec kBox ON " ) ;

else
mChec kBox . s etText ( " Chec kBox OFF " ) ;

.
, .
. 6. 1 1 .

1 12

. 6 . 1 1 . Che c kBox

6. 5.4. ToggleButton
Toggl eButton - : " " "
" ON/OFF LD
, ON .
ToggleButton - android : textOff andro i d : textOn,
.
s e tTextO f f ( ) setTexton ( ) .
s e tChe c ked ( bool ean checked)
. Togg leBut ton -
onChe c kedChanged ( ) .

Create New Proj ect


:

Proj ect name - ToggleButt onApp;

Application name - ToggleButton

Package name - com . s arnp l e s . toggl ebutton;

C reate Activity - Toggl eBut tonActivi ty.

S arnple;

,
Toggl eButton extView (
6. 1 8).

1 13

< ?xml ve r s i on= " l . O " encoding= " ut f - 8 " ?>


<LinearLayout xmlns : android= " http : / / s chema s . androi d . com / apk / res / android"
android : o rientat ion= "vert i ca l "
android : layout width= " f i l l pa rent "
_
_
android : layout he i ght= " fi l l parent " >
_
_
<ToggleButton
android : id= " @ + id / button
android : layout he ight= "w rap content "
_
_
android : layout width= " fi l l parent " / >
_
_
<TextView
android : id= " @ + i d / text "
android : layout wi dth= "wrap content "
_
_
android : layout he ight= "wrap content " / >
_
_
< / Linea rLayout>


CompoundBut ton . OnChec kedChange
L i s tene r .

onCheckedChanged ( ) ,
.
i s Checked.
6. 1 9.

package com . s amp l e s . toggl ebut ton ;


import android . app . Ac t ivi t y ;
import android . os . Bundle ;
import android . widget . Compoundutton ;
import android . widget . ToggleButton ;
import android . widget . TextView ;
pu l i c c l a s s Togg leButtonActivity extends Act ivity
implements Compoundutton . OnChe c kedChangeLis tener
Togg l eButton mut ton ;
TextView mLabe l ;

1 14

@ Ove r r i de
pu i c void onC rea t e ( Bund l e s aved i n s t ance S t at e )
s upe r . onCreate ( s avedinstanc e S t a t e ) ;
s e t ContentView ( R . l a yout . ma i n ) ;
mut ton

( ToggleBut t on ) f indVi ewBy i d ( R . id . button ) ;

mut ton . s e tOnChec kedChangeLi s t ene r ( thi s ) ;


mLabe l

( TextView ) f i ndV i ewByi d ( R . i d . text ) ;

@ Ove r ride
pu i c void onChec kedChanged (
Compoundutton but tonView,
if

boo l ean i s Checked )

( i s Chec ked )
mLabe l . s e tText ( " Button checked " ) ;

else
mLabe l . s e tText ( "Button unchecked " ) ;

.
OFF ON LD-,
. 6. 1 2 .

. 6 . 1 2. Toggl eBut ton

1 15

6.5.5. /mageButton
ImageButton (
). IrnageButton Button,
,
.
android : s rc

< IrnageButton>

s e t irnageResource ( int ) .

. C reate New P roject


:
D

Project name -

Application name -

Package name -

C reate Activity -

ImageButtonApp;
IrnageButton Sarnple;

. sarnpl es . imagebutton;

IrnageButtonAct ivi ty.


IrnageButton 6.20.

< ? xrnl ve r s i on= " . 0 " encoding= " ut f- 8 " ? >


<Linea rLayout xrnlns : android= " http : / / s chema s . android . com/ apk/ re s / andro id"
android : orientat ion="ve r t i ca l "
andro id : layout_width= " f i l l_pa rent "
andro id : layout_he i ght= " fi l l_pa rent " >
< ImageButton
android : id= " @ + id/button "
android : l a yout_width= "wrap_content "
android : l a yout_he ight=" wrap_content"
androi d : s rc= " @ drawable/play " / >
< / Linea rLayout >

res/drawa\e/
( r: CD-ROM
Resources/lmages/ - play.pg pause.pg).

Ima geButtonAct i vi ty

, 6.2 1 .

116

package com . sample s . imagebutton;


import android . app . Activi t y ;
import android . os . Bundle ;
import android . view . View;
import android . widget . ImageBut ton ;
pul i c c l a s s ImageButtonAct ivity extends Act ivity
ImageButton button ;
t rue ;

boolean mPlay
@ Ove rride

pu l i c void onCreate ( Bundle s avedins tance State )


super . onCreate ( savedinstanceState ) ;
setContentView ( R . layout . main ) ;
button

( ImageButton ) findViewByid ( R . id . button ) ;

1 1 n
but ton . s e t imageRe source ( R . drawale . play) ;
but ton . setOnCl ickLis tener ( new \Tiew . OnCl i ckLis tene r ( )
pu l i c void onC l i c k (View v )
1 1

i f (mPlay)
button . s e t imageResource ( R . drawal e . pause ) ;
else
button . se t imageResource ( R . drawale . play) ;
mPlay

! mPlay ;

n n n. n
n, n . 6. 1 3 .

117

. 6. 1 3 . ImageBu t t on

6 . 6 .
Adroid

s t

TabWidget

( . 6. 1 4 ) .

Framelayout
Ta bHost

TabWidget

. 6 . 1 4.

s t
-. s t
abW i d g e t . ,
.
- s t . ,
s t .
.

1 18

s t
.
abHos t :
D s etup ( )

- .
, s t

findVi ewByi d ( ) ;

D addTab ( )

- ;

D s e tCurrentTab ( )

- .


,
,
.

TabWidget .

TabSpe c:
TabHos t . TabSpec spec

tabs . newabSpec ( " tagl " ) ;

spec . s etContent ( R . i d . tabPage l ) ;


spec . s et i ndicat o r ( " Document 1 " ) ;
tabs . addTab ( spec ) ;

C reate New
Proj ect :
D

Proj ect

Application name - TabHost

Package

Create Activity - TabHos tAct ivity.

TabHos tApp;
Sample;

- . samples . t abhos t ;


6.22.

< ? xrnl ve r s i on= " . 0 " encoding= " ut f - 8 " ? >


<TabHost xrnl ns : android= "http : / / s chernas . android . com/apk/ res / andro id"
andro id : id= " @ + id/ tabhos t "
android : l ayout_width= " f i l l_pa rent "
android : layout_he ight= " fi l l_parent " >
<TabWidget android : id= " @ android : id/ tabs "
andro id : la yout_width= " fi l l_parent "
android : l ayout_he i ght = " wrap_content " / >

1 19

< FrameLayout android : id= " @ android : id/ tabcontent "


android : l ayout_width= " f i l l_parent "
androi d : layout_he i ght= " fil l_pa ren t "
android : paddingTop= " 62px " >
<EditText android : id= " @ +id/tabPage l "
android : layout_width= " f i l l_parent "
android : layout_he ight= " fi l l_pa rent " / >
<EditText android : id= " @ + id/ tabPage 2 "
andro id : layout_width= " f i l l_pa rent "
android : layout_he i ght= " fi l l_pa rent " / >
< / FrameLayout>
< /TabWidget >
< / TabHos t >

aostActivi t y
s t .
6.23 .

package com . samples . tabhos t ;


import android . app . Act ivi t y ;
import android . os . Bundle ;
import android . widget . TabHos t ;
pul i c c l a s s TabHos tActivity extends Act ivity
@ Ove rride
pu l i c void onCreate ( Bundle s avedinstanceState )
supe r . onCreate ( savedinstanceState ) ;
setContentView ( R . layout . ma i n ) ;
TabHost tabs

( TabHos t ) f indViewByid ( R . id . tabhos t ) ;

tabs . s etup ( ) ;
TabHos t . TabSpec spec

tabs . newTabSpec ( " tag l " ) ;

spec . s etContent ( R . id . tabPage l ) ;


spec . s et indicator ( " Document 1 " ) ;
t abs . addTab ( spec ) ;

1 20

6
spec=tabs . newTabSpec ( " tag2 " ) ;
spec . s etContent ( R . i d . tabPage2 ) ;
spec . s et indicator ( " Document 2 " ) ;
tabs . addTab ( spec ) ;
t abs . s etCurrentTab ( O ) ;

.
s t . 6. 1 5 .

Enter text. .

. 6. 1 5. TabHost

6 . 7 .
Android :
Cl Progre s s Bar;
Cl Rat ingBa r;
Cl Seekar.

. 6. 1 6.
Ra tingBa r ( ) SeekBa r ()
Progres sBa r As SeekBar. AsSeekBar

121


Rat ingBar SeekBar.

View
ProgressBar

Rati ng Bar
SeekBar

. 6. 1 6.

Progres sBa r, Rat i ngBa r Seekar

6. 7 1 ProgressBar
.

ProgressBar
. ,
Progres sBar:
D s e t Progre ss

( ) - ;

Cl get progre s s ( ) - ;

- ;

D increment Progre s sBy ( )


D setMax ( )

- .

.
Android andl e r
.
-
andl e r .
andle r, , ,
(, Progre s sar)
.
andler,
obtaine s s age ( ) , Mes s age
:
Handle r h ;
1 1
Mes sage msg
mandler . obta ines s age ( ) ;
=

1 1 Handl e r
h . s endes sage (ms g ) ;

1 22


:
s ende s s age

andler

( ) - n (

);
( ) - n
, , n (
),
n ;

sende s s ageAt FrontOfQueue

s ende s s a geAtT irne ( )

- n
!\'I ;

s ende s s ageDe layed ( )

- n n ,
.

, andle r
handl ee s s age ( ) ,
.
Handl er h ;
h

new Handle r ( )
@ Ove r ride
pul ic vo id handleMes s age ( Mes sage rns g )
1 1

n n Progre s sBar,
n ( n n
n , 1 ) n
andl er .
n Create New Project
:

Proj ect name -

Application name -

Package name - . sarnples . progres sbar;

C reate Activity -

Progres sBarApp;
Progres sar Sarnple;

ProgressBarAct ivity.

LinearLayout,
ProgressBar n, Stari Stop, n 6.24.

1 23

< ? xml ve rs i on= " l . O " encoding= " ut f - 8 " ?>


<Linea rLayout xmlns : android= " http : / / schemas . android . com/ apk/ res / android"
android : layout_width= " fi l l_pa rent"
andro id : layout_he i ght= " fi l l_pa rent "
android : gravity= " cent e r "
android : orientat i on= "ve r t i ca l " >
< Progre s sBar andro id : id= " @ +id/progre s s "
s tyle= " ? android : at t r /progre s sBarStyleHori zontal "
android : layout_width= " fi l l_pa rent "
android : layout_he ight= "wrap_content "
<LinearLayout
android : id= " @ + id/ Linea rLayoutO l "
android : layout_width= "wrap_content "
android : layout_he ight= "wrap_content "
android : o rientation= " hori zonta l "
andro id : padding= " l Opx " >
<Button
android : id= " @ +id /button s t a rt "
android : l ayout_he i ght=" wrap_content "
android : text= " Start "
androi d : layout_width= " B Opx " / >
<Button
android : id= " @ + id/button_s top "
androi d : layout_he i ght= " wrap_conten t "
android : text= " S top "
androi d : layout_width= " B Opx " / >
< / Linea rLayout>
< / Linea rLayout>

ProgressBarAct ivi ty n,
, Q Progres sBar.
P rogres sBarAct ivity n 6.25 .

package com . android . progre s sba r ;


import android . app . Ac t ivity ;
import android . os . Bundle ;

1 24

import andro id . os . Handler ;


import android . os . Me s s age ;
import android . ut i l . Log ;
import android . view . View ;
import andro id . view . Vi ew . OnGl i ckLi s tene r ;
import android . widget . Button ;
import android . widget . Progre s s Ba r ;
pu l i c c l a s s ProgressBarAct ivity extends Activity
private Progres sBa r mProgressBa r ;
pr ivate bool ean mi sRunning
private Handler mandle r ;

fa lse ;

@Ove r ride
pul ic void onCreate ( Bundle s avedi ns tanceState )
supe r . onCreate ( s avedinstanceStat e ) ;
s etContentView ( R . l ayout . main ) ;
mProgres sBar

( Progres s Ba r ) findViewByid ( R . id . progre s s ) ;

final Button ButtonStart


( Button ) findViewByid ( R . id . button_s tart ) ;
final Button ButtonStop

( Button ) f indViewByid ( R . id . button_s top ) ;


mandler

new Handler ( )

@Ove rride
pu l i c void handleMes s age ( Me s sage ms g )
mProgre ssBa r . inc rement ProgressBy ( l ) ;
};
1 1 ProgressBar

ButtonStart . s etOnCl ickLis tene r ( new OnClickLis tene r ( )


@Ove rride
pu l i c void onCl i c k ( View v )
onS tart ( ) ;

1 1 P rogre ssBar

ButtonS top . setOnC l i ckLis tene r ( new OnCl ickL i s tene r ( )


@Ove r ride
pu l i c void onC l i c k ( View v )

1 25


onStop ( ) ;

1 1
pu l i c void onStart ( )
supe r . onStart ( ) ;
mProgre s s Ba r . setProgre s s ( O ) ;
1 1
Thread background = new Thread ( new Runnale ( )
pu l i c vo id run ( )
whi l e

(mi s Running )

try {
Thread . s leep ( l O O ) ;
catch

( I nte rruptedException )

Log . e ( "ERROR " ,

" Thread Int e r rupted " ) ;

mandle r . sende s s age (mandl er . obtaine s s age ( ) ) ;

}) ;
mi sRunning

t rue ;

bac kground . s t a rt ( ) ;

pu l i c void onStop ( )
supe r . onStop ( )
mi sRunn ing

fa l s e ;

.
. 6. 1 7.

6. 7 2 SeekBar
.

SeekBa r - (),
. seekBa r Progressar.

,
.

1 26

. 6 . 1 7. Progres s Ba r

s e e kar
SeekBa r . OnSee kBarChangeLi s t ener.
,
Ac t i vi t-:
D onProg re s s Changed ( )

- ,

;
D onS t a rtTrackingTouch ( )

- ,

;
- ,
.

D onS topT rack ingTouch ( )

s e e kBar,
, - S e e kBa r . OnS e e kBa rChange L i s t ener.
' s e e ka r Create
New Proj ect :
D

Proj ect name -

Application name - SeekBar

Package name - . s ampl e s . s e e kba r ;

Create Activity - S e e kBa rAc t i v i t y .

S e e kBar;
S amp l e ;

127

Lia rLayout,
SeekBar ,
, 6.26.

< ? xrnl ve rs ion= " l . O " encoding= "utf- 9 " ? >


<LinearLayout xmlns : android="http : / / s chema s . andro id . co /apk / re s / android"
andro id : orientati on="vert i ca l "
andro id : layout_width= " fi l l_pa rent "
andro id : layout_he i ght= " fi l l_parent "
android : gravity= " cent e r "
android : padding= " l Opx " >
<SeekBa r
android : id= " @ + id/seek bar "
android : layout_he ight= "wrap_content "
android : la yout_width= " fi l l_pa rent " / >
<LinearLayout
android : layout_width= "wrap_content "
android : layout_he ight= "wrap_content "
android : padding= " l Opx " >
<TextView
android : layout_width= "wrap_content "
android : layout_he ight="wrap_content "
android : text= "Value :
android : textS tyle= "bold " />
<TextView
android : id= " @ +id/ text value "
android : layout_width= "wrap_content "
android : layout_he ight= "wrap_content "
android : text= " O "
android : textStyle="bold" />
< / LinearLayout>
< / LinearLayout>

seekBarActivity ,
.
6.27.

1 28

pac kage com . sample s . seeka r ;


import android . app . Ac t ivi t y ;
import andro id . os . Bundle ;
import android . widget . SeekBa r ;
import android . widget . TextView ;
pu l i c c l a s s S e e ka rAct ivity extends Act ivity
implements SeekBa r . OnSeekBa rChangeL i s tener
TextView mTextVa lue ;
@ Ove rride
pul i c void onCreate ( Bundl e s avedins tanceState )
s upe r . onCreat e ( s avedi nstance State ) ;
s etContentView ( R . layout . ma in ) ;
final SeekBar see kBa r

( Seeka r ) findViewBy id ( R . id . s e e k ba r ) ;
_

s e e kBar . s etOnSeekBa rChangeLi stene r ( thi s ) ;


mTextVa l ue

( TextView ) f indViewByi d ( R . ia . text va lue ) ;


_

mTextVa lue . s etText ( " O " ) ;

1 1 n
@ Ove rride
pu l i c void onStopTrackingTouch ( Se e kBar seeka r )

mTextVa l ue . s e tText ( S t ring . va lueO f ( seekBar . getProgres s ( ) ) ) ;

1 1 , OnSeekBarChange L i s tener
11 n n
@ Ove rride
pul i c void onProg res s Changed ( See kBar seekBa r ,
bool ean fromU s e r )

int prog res s ,

1 / TODO Auto-gene rated method stu


/ 1 TODO
@ Ove rride
pu l i c void onS ta rtTrackingTouch ( S eekBar seekBa r )

1 1 TODO Auto- gene rated method s t u


1 1 TODO

1 29

. 6. 1 8. SeekBar

.
. 6 . 1 8 .
.

6. 7 3 RatingBar
.

Rat i nga r - AsSeekBar Progre s sBar,


.
(),

Rat inga r. RatingBa r
" "
,
setNumStars ( int )
getRat ing ( )

Rat ingBa r:

- ;

- ;

i s i ndicator ( )

- Rat ingBa r " ";

s e tRa t ing ( floa t )

- ;

s e t StepS i z e ( float )

- .

, Rat ingBa r OnRat i ngBa rChange


Lis tener .

1 30

Rat ingBa r
Create New Project :
D Proj ect name - Rat ingBar;
D Application name - RatingBar
D Package name -

Sample;

sample s . rat ingbar;

D Create Activity - RatingBarAct ivity.


LinearLayout,
Progre s sar, , Up Down,
( 6.28).

< ? xrnl ve r s i on= " l . O " encoding= "ut f- 8 " ?>


<LinearLayout xrnlns : android= " http : / / s chernas . android . com/ apk / re s / andro id"
android : or i entat i on= "ve r t i ca l "
andro id : layout_width= " fi l l_pa rent "
android : layout_he i ght= " fi l l_parent "
android : gravity= " center " >
<Rat ingBar
android : id= " @ + id/ rat ing "
android : layout_width= " wrap_content "
android : layout_height= "wrap_content " / >
<LinearLayout
android : layout_width= " wrap content "
android : layout_he i ght= "wrap_content "
andro id : padding= " 2 0px " >
<But ton
android : id= " @ + id/button_up "
android : layout_he ight= "wrap_content "
android : text= "Up "
android : layout_width= " Opx " / >
<Button
android : id= " @ + id/button down "
android : layout_hei ght="wrap_content "
android : text= " Down "
android : layout_width= " Opx " / >
<TextView
android : layout_width= "wrap_content "

131


android : layout_he i ght="wrap content "
android : text= "Value :
android : padding= " ! Opx "
android : textStyle= "bold " />
<TextView
android : id= " @ +id/ text value "
android : l ayout_he i ght = "wrap_content "
android : layout_width= " 4 0px "
android : textStyle= "bold " / >
< / LinearLayout>
< /LinearLayout >

RatingarActivity
n U Down, n
Rat i ngBar, OnRat i ngBa rChangeLi s tene r
( 6 .29).

package com . sample s . rat ingba r ;


import android . app . Activi t y ;
import android . os . Bundle ;
import android . view . View ;
import android . view . View . OnCl i c kLis tene r ;
import android . widget . Button ;
import android . widget . Rat ingBa r ;
import android . widget . TextView ;
import android . widget . Rat i ngBa r . OnRat ingBarChangeListene r ;
pul i c c l a s s RatingBarAct ivity extends Act ivity
private static final int NU STARS
private float mStep
p r ivate float mRat ing

5;

0 . 5f;
l . Of;

@ Ove r ride
pu i c void onCreate ( Bundle savedins tance State )
supe r . onCreate ( s avedinstance State ) ;
setContentView ( R . layout . main ) ;

1 32

6
fina l Rat i ngBar ratingBa r l
( Rat ingBa r ) findVi ewByid ( R . id . rating ) ;
final Button buttonUp
( Button ) f indViewByid ( R . id . button up ) ;
_

final But ton but tonDown

( Button ) f indViewByid ( R . id . button down ) ;


_

f inal TextView l abe l

( TextView) findViewByid ( R . id . text va lue ) ;


_
ratingBa r l . setNumStars ( NU STARS ) ;
_
rat ingBa r l . setRating ( mRat ing ) ;
rat ingBa r l . s e t S tepS i z e ( 0 . 5 f ) ;
l abe l . setText ( St r ing . valueO f (mRa t i ng ) ) ;
buttonUp . s etOnC l i c kL i s tener ( new OnCl i ckLis tene r ( )
@ Ove rride
pu l i c vo id onC l i c k ( View v )
mRating += mS t ep ;
if

(mRating > NUM STARS )


_
mRating
NU STARS ;
_
rat ingBa r l . s etRat ing (mRating ) ;

but t onDown . s etOnC l i c kL i s tene r ( new OnC l ickListene r ( )


@ Ove r r ide
pu i c vo id onC l i c k ( View v )
mRating
if

-=

mS t ep ;

(mRating < 0 )
mRat ing

rat ingBa r l . setRa t ing (mRa t i ng ) ;

ratingBa r l . s etOnRat ingBa rChangLis tene r (


new OnRat ingBa rChangeLis tener ( )
@ Ove rride
pu i c vo id onRat i ngChanged (
Rat ingBa r rat ingBa r ,
boolean frornU s e r )

f loat rat ing ,

label . setText ( S t ring . valueOf ( ratingBa r l . getRating ( ) ) ) ;


mRating

rat ingBar l . getRa t ing ( ) ;

1 33

.
. 6. 1 9 .
Rat ingBa r : ,
Rat ingBa r , Up
Down.

. 6 . 1 9 . Rat ingBar

6 . 8 .

:
D

Ana logClock;

D i g i t a l C l ock;

Chronorne t e r .

D i g i t a l C l o c k
Ana logClock. ,
. Ana logClock,
D i g i t a l C l o c k Chronorne t e r . 6.20.

1 34

Object

-----,

View

------,

TextView

.------,
f------1 AnalogCiock

DigitaiCiock
'------1 Chronometer

. 6.20. AnalogClock, Digi talClock Chronorneter

6.8 . 1 . A nalogC/ock Digita/Ciock


AnalogClock DigitalClock
.
C reate New Proj ect
:
D

Proj ect name - Ana logClockApp;

D Application name - AnalogClock


D Package name -

Sarnple;

. samples . ana logclock;

D C reate Activity - AnalogClockAct ivi ty.


6.30.

< ?xrnl ve r s i on= " . 0 " encoding= " ut f- 8 " ?>


<Relat iveLayout
xrnlns : andro id= "http : / / s chernas . android . com/ apk/ res /androi d "
android : orientation= " ve r t i cal "
andro id : layout_width= " fi l l_parent "
andro id : layout_he i ght= " fi l l_parent " >
<AnalogClock android : id= " @ +id/analog "
android : layout_width= " fi l l_parent "
android : layout_he i ght = "wrap_content "
android : layout_centerHori zonta l= " t rue "
android : layout_a l i gnParentTop= " t rue " / >
<Digi talClock android : id= " @ + i d/digital "
android : layout_width= " wrap_content "
android : la yout_he ight= "wrap_content "
android : layout_centerHori zontal= " t rue "

1 35

android : l a yout_be l ow= " @ i d /ana l o g "


android : t extStyle= " bo l d " andro id : t ext S i z e= " 4 0 s p " / >
< / R e l a t i veLayout >

.
. 6 .2 1 .

. 6.21 .

6 . 8 . 2 . Chronometer
Ch ronomet e r - .
,
.

s t art

Ch ronome t e r :

( ) - ;

s t op ( )

- ;

( ) - . " M M : SS" " H : M M : SS"

s e t Fo rma t

Chronome t e r
:
getOnChronome t e rT i ckLi s tene r ( ) ;
s e t OnChronome t e rT i c k L i s tene r ( ) .

OnCh ronome t e rT i ckLi s tener,

1 36


.
, Chronometer,
Create New Project :

Project name - Chronomete rApp;

Application name - Chronometer Sample;

Package name - . samples . chronometer;

C reate Activity - ChronometerAct ivi ty.

Linea rLayout,
Chronometer - Start,
Stop Reset ( 6 .3 1 )
.

< ?xml ve r s i on= " l . O " encoding= " ut f- 8 " ?>


<LinearLayout xmlns : android= "http : / / s chemas . android . com/ apk / re s / android"
andro id : orient a t i on= "ve r t i ca l "
andro id : la yout_width= " fi l l_pa rent "
android : la yout_he i ght= " fi l l_parent "
android : gravi t y= " cent e r " >
<Chronometer
android : id= " @ + id/chronometer"
android : layout_width= "wrap_content "
apdroid : la yout_he ight="wrap_content "
android : text S i z e= " px "
android : gravi ty= " cente r " / >
<Linea rLayout
android : id= " @ + id/LinearLayout O l "
android : l ayout_width= " wrap_cont ent "
android : l ayout_he ight= "wrap_cont ent " >
<But ton
android : id= " @ + id/button start "
android : la yout_width= " wrap_content "
android : l a yout_he ight= "wrap_content "
android : text= " S t art " / >
<But ton
android : id= " @ + id/button_s top "
android : layout_width= " wrap_content "
android : la yout_he i ght= "wrap_content "
android : text= " S top " / >

137

<Button
android : id= " @ + id/button res et "
android : la yout_width= "wrap_cont ent "
android : l ayout_he ight = "wrap_content "
android : text= " R se t " / >
< / Linea rLayout >
< /Linea rLayout>

ChronometerActivity
, , 6.32.

pac kage com . sample s . chronomete r ;


import android . app . Ac t ivi t y ;
import android . os . Bundle ;
import android . os . S ys t emClock ;
import android . view . View ;
import android . view . Vi ew . OnC l ickLis tene r ;
import android . widget . But ton ;
import android . widget . Chronomete r ;
pu i c c l a s s ChronometerAc t ivity extends Activity
@ Ove rride
pu i c void onCreate ( Bundle s avedlns tanceState )
supe r . onCreate ( savedlnstance Stat e ) ;
setContentView ( R . layout . ma in ) ;
1 1
final Button buttonStart
( Button ) findViewByld ( R . id . button_s tart ) ;
final Button buttonStop
( Button ) findViewByld ( R . id . button_s top ) ;
final Button buttonRe set
( Button ) findViewByid ( R . i d . button_reset ) ;
final Chronometer mChronometer
( Chronometer ) findViewByld ( R . id . chronome te r ) ;
1 1
but tonStart . s e tOnC l i c kL i s tene r ( new OnC l ickLis tene r ( )
@ Ove rride

1 38

6
pu l i c vo id onC l i c k ( V i ew v )
mCh ronome t e r . s t a r t ( ) ;

1 1
but tonStop . s e tOnC l i c kL i s t ene r ( new OnC l ickLi s t ene r ( )
@ Ove r r i de
pu l i c vo i d onC l i c k ( V i ew v )
mCh ronome t e r . s t op ( ) ;

1 1
but tonRe s e t . s e tOnC l i c kLi s tene r ( new OnC l i c k L i s tene r ( )
@ Ove r r i de
pu l i c vo i d onC l i c k ( V i ew v )

mCh ronome t e r . s e t B a s e ( S y s temClo ck . e l ap s edRe a l t ime ( ) ) ;

.
Chronome t e r . 6 .22.

. 6 . 2 2 . Chronome t e r

.7

-

-,
,
.

7 .1 .
,

.
ArrayAdapter<T>.
, , :
S t ring [ ] items= { " one " ,

" t o " , " t re e " } ;

ArrayAdapte r<St r ing> adapte r

new ArrayAdapt er<Str ing>

( thi s , android . R . layout . s imple_l i s t_item_l , i t ems ) ;

ArrayAdapt e r :
D Context - , Act ivity.
context
. context
,
, , , ,
. .;
D .
- s imp le_l i s t_item_l .
- ,
android . R . layout, s imple_spinne r_dropdown_i tem, s imple

1 40
g a l l e ry i tem, s imple_l i s t _ i tern_checked

., , ,

L i s t <T >

ArrayAdapte r toString ( )

. R . l ayout . s irnple_l ist_
i tern_ 1 TextVi ew, ,
, Li s tView (
- ).

,
ArrayAdapter, getView ( )
, .

7 .2 .

Adroid :
AutoCornpl eteTextView;
Mult iAutoCornpl eteTextView.

extView
Editext .
. 7 . 1 .

TextView
Ed itText

. 7.1 .

7 2 1 A uto Complete TextView


.

AutoCornpleteTextView

.
,
.
-

141

AutoCompleteTextView Editext,
.
, AutoComple teTextView and roid : completion
Threshold ,
,
. AutoCompleteTextView
, setAdapte r ( ) .
AutoComplet eTextView
Create New Proj ect
:

Proj ect name - AutoCompleteTextViewApp;

Application name

Package name - . samples . autocompletetextview;

Create Activity - AutoComplet eTextViewAct ivity.

AutoComple teTextViewSample;

7. 1 .

< ?xml ve r s i on= " . 0 " encoding= " ut f- 8 " ?>


<LinearLayout
xmlns : android= " http : / / s chema s . android . com/ap k / res / android"
android : orientat ion= "vert ical "
android : l ayout_width= " fi l l_parent "
andro id : layout_he ight= " fi l l_pa rent " >
<TextView
android : l ayout_width= " fi l l_parent "
android : l ayout_he i ght="wrap_content "
androi d : id= " @ + id/ text "
<AutoComplet eTextView
andro id : id= " @ +id/auto_complete "
android : l ayout_width= " fi l l_pa rent "
android : l ayout_he ight= "wrap_content "
android : completionThre shold= " " / >
< /Linea rLayout>

AutoCompleteTextView
7.2.
(,
),
AutoCompleteTextView.

142

package com . samples . autocompletetextview ;


import android . app . Act ivity ;
import android . os . Bundle ;
import android . t ext . Edital e ;
import android . t ext . TextWat che r ;
import android . widget . ArrayAdapte r ;
import android . widget . AutoCompleteTextView ;
import android . widget . TextView ;
pu l i c c l a s s AutoCompl eteTextViewActivity extends Act ivi t y
implements TextWat che r
TextView mText ;
AutoCompleteTextView mAutoComplete ;
final St ring [ ] mContacts
" Jacob Anderson " ,
"Emma Greenman " ,

" Emi ly Duncan " ,

"Mi chae l Ful l e r " ,

" Joshua Ha r r i s on " , " Madi s on Johnson " ,

"Mat thew Cotman " ,

"Ol ivia Laws on " , "Andrew Chapman " ,

"Mi chael Honeyman " , " I sabe l l a Jackson " , "Wi l l i am Patterson " ,
" Jos eph Godwi n " , " S amantha Bush " ,

"Ch r i s t ophe r Gat eman " } ;

@ Ove rride
pu l i c void onCreate ( Bundle s avedinstance State )
super . onCreate ( savedins tanceState ) ;
setContentView ( R . layout . ma in ) ;
mText

( TextView ) findViewByid ( R . id . text ) ;

mAutoComplete= (AutoCompleteTextView ) findViewByid (


R . id . auto_complete ) ;
mAutoCompl ete . addTextChangedLi stener ( thi s ) ;
mAutoCompl ete . setAdapter ( new ArrayAdapter< S t ring> ( thi s ,
android . R . layout . s imple_dropdown_item_l l i ne , mContacts ) ) ;

pul i c void onTextChanged (


Cha rSequence s , int s t a rt , int be fore , int count )
mText . s etText (mAutoComplete . getText ( ) ) ;

pul i c void beforeTextChanged (


CharSequence s , int s t a rt , int count ,

int a fte r )

1 43

pul i c void afte rTextChanged ( Edi tale s )

.
(. 7 .2).

joshua Ha rrison
joseph Godwi n

. 7.2. Aut oCompleteTextVi ew

7 2 2 MultiA uto Complete TextView


.

Mu lt iAutoCompleteTextView -
,
AutoComplet eTextView,
, .
setTokeni zer ( ) :
Mu lt iAutoCompleteTextView textView
( Mult iAutoCompleteTextVi ew ) findViewByid (
R . id . Mul t iAutoCompl eteTextViewO l ) ;
textView . s etAdapte r ( adapte r ) ;

textView . s etTokeni z e r ( ew Mul t iAutoCompl eteTextVi ew . CommaTo ke i z e r ( ) ) ;

1 44

Mul t iAutoCornpleteTextVi ew.


Create New Project :
Proj ect name - Mul t iAutoCornpleteTextVi ewApp;

Application name - Mult iAutoCornple teTextView

Package name - corn . s arnpl es . rnul t iautocornpletetextview;

Create Activity - Mul t iAutoCornpleteTextViewActivi t y.

Sarnple;

7.3 .

< ? xrnl ve r s i on= " l . O " encoding= " u t f- 8 " ?>


<LinearLayout xrnlns : android= " http : / / s chernas . android . com/apk / re s / android"
android : orientation=" vertica l "
android : l ayout_width= " fi l l__parent "
andro id : layout_he ight= " fi l l__parent " >
<Mult iAutoCornpleteTextView
android : id= " @ + id/MultiAutoCornpleteTextViewO l "
android : la yout_he ight= "wrap_content "
android : layout_width= " fi l l_parent " / >
< / LinearLayout>

,
s e tToken i z e r ( ) :
textView . setTokeni zer ( new Mul t iAutoCornpleteTextView . CommaToken i z e r ( ) ) ;

Mul t iAutoCornplet eTextView


AutoCornpleteTextView 7.2.
,
( 7 .4).

package corn . sarnples . autocornpletetextview ;


irnport android . app . Activi t y ;
irnport android . os . Bundle ;
irnport android . widget . Mult iAutoCornpleteTextVi ew ;
irnport android . widget . ArrayAdapte r ;

1 45

pu l i c c l a s s Mult iAutoCornpleteTextViewActivity ext ends Activity


1 1

final St ring [ ] rnContacts


"Ande rson, Jacob" , " Duncan, Erni ly" , " Fu l l e r , Michae l " ,
" Greenrnan, Ernrna " , "Harrison , Joshua " , " Johnson , Mad i s on " ,
" Cotrnan , Matthew" , "Laws on , Olivi a " , "Chaprnan , Andrew " ,
" Honeyrnan , Mi chael " , " Jackson, I sabe l l a " , " Patterson , W i l liarn" ,
" Godwin , Joseph" , "Bush, Sarnantha " , "Gaternan , Chri s t ophe r " } ;
@ Ove rride
pu l i c void onC reate ( Bundl e s avedinstance State )
super . onCreate ( savedins tance State ) ;
setContentView ( R . layout . rnain ) ;
ArrayAdapt er<St ring> adapter
new ArrayAdapter<String> (
thi s , android . R . layout . s irnple_dropdown_itern_l l ine , rnContacts ) ;
Mult iAutoCornpl eteTextView textView
(Mult iAut oCornpleteTextView ) f indViewByid (
R . id . Mult iAutoCornpleteTextViewO l ) ;
textView . s etAdapt e r ( adapte r ) ;
textView . s etTokeni z e r (
new Mult iAutoCornplet eTextVi ew . CornrnaTokeni ze r ( ) ) ;

Harrison, joshua
joh nso n, Madison
Godwi n, joseph

. 7 . 3 . Mult iAutoCornplet eTextVi ew

146

.
. 7.3 . ,

.

7 . 3 .
- Android :
L i s tVi ew;
GridVi ew;
Ga l l e ry;
Spinne r;
S l i dingD rawe r.

, ( S l i dingD rawe r)
Adapt e rVi ew.
.
. 7.4.

Object

1
-ViewGro u p--,1

-----,

View

---

--,

---

1-------1 AdapterView

,----....,
Abs li stView 1

AbsS p i n n e r

'------1 S l i d i n g D rawer

,----....,
G ridView
ListView

1
1

-----,

Gallery

Spinner

1
1

. 7.4.

Adapte rView
:

AdapterVi ew -

Adapter,

Vi ewGroup,

147

Adapter
(, ) AdapterVi ew, .
Adapter ,
Cursor ArrayAdapt e r
.
,
, ,
SQLite. ,
AdapterView View
Adapt er.
15.
Curso rAdapt er

Adapt e rView A s L i s tVi ew,


,
( L i s tView GridView) , As Spinner -
( Gallery Spinne r) .

7 3 1 ListView
.

L i s tView .
L i s tView L i s tAdapter.
,
Act ivity, ListView
L i s tAct i vi ty.
L i s tAct ivity ,
, ,
, . . L i s tAct ivity
L i s tVi ew,
. L i s tActivity
, ,
( - ).
Li stAct ivity
, L i s tAdapter. Android
:
S impleAdapt er;
S impleCursorAdapte r.
s impleAdapt e r
. S impleCursorAdapt e r , ,

15.

1 48

ListView
Create New Project :
D Project name - L i s tVi ewApp;
D Application name - ListView
D Package name -

Sample;

. samples . l i s tvi ew4 ;

D Create Activity - Lis tViewAct ivity.


LinearLayout ' L i s tView
TextView ,
7 . 5 .

< ? xrnl ve r s i on= " . 0 " encoding= " ut f- 8 " ?>


<Linea rLayout
xrnlns : andro id= " http : / / s chernas . android . com/ apk / res /androi d "
android : orientat ion= "vert ical "
andro id : layout_width= " fi l l_pa rent "
andro id : l ayout_height= " fi l l_pa rent " >
<TextView
android : id= " @ + id/text Select "
andro id : l ayout_width= " fi l l_pa rent "
android : layout_height= "wrap_content "
android : text Style= "bold" / >
<ListView
android : id= " @ andro id : id/ l i s t "
android : layout_width= " fi l l_pa rent "
android : layout_he ight= " fi l l_pa rent "
android : drawSelectorOnTop= " false " / >
< / Linea rLayout>

L i s tAct ivity ,
, .

package corn . samples . l i stview;


irnport android . app . Lis tAct ivi t y ;
irnpo rt android . o s . Bundle ;

1 49

-
import android . view . View;
import andro id . widget . ArrayAdapt e r ;
import android . widget . ListView ;
import andro id . widget . TextView ;
pu l i c c l a s s L i s tVi ewAct ivity extends L i s tAct ivity
,private TextView mTextView ;
St ring [ ] mCont acts
" Jacob Ande rson" , " Emi ly Duncan " , "Mi chael Fu l le r " ,
" Emma Greenman " ,

" Jos hua Harri son " ,

"Mat thew Cotman " ,


" Daniel Honeyman " ,

"Olivia Lawson " ,

"Madi son Johnson " ,


"Andrew Chapman" ,

" I s abella Jackson " , "Wi l l i am Patterson" ,

" Jos eph Godwi n " , " S amantha Bus h " , " Chris tophe r Gateman " ) ;
@ Ove rride
pu l i c void onC reate ( Bundle s avedinstance State )
super . onCreate ( savedinstanceStat e ) ;
setContentView ( R . layout . ma in ) ;
setLis tAdapte r ( new ArrayAdapter<String> (
thi s , android . R . layout . s imple_l is t_item_l , mContacts ) ) ;
mTextView

( TextView ) findViewByid ( R . id . textSelec t ) ;

pu l i c void onL i s t i temC l i c k (


Lis tVi ew pa rent , View v,
mTextView . s etText ( " Select :

int pos i t ion , long i d )


+ mContacts [ po s i t ion ] ) ;

.

(. 7.5).

7 3 2 Spinner
.

Spinner - m ( ) Android.
-
, ,
Lis tView, .
Spinner, ,
Spinner, - .

1 50

. 7.5. L i s tView

on i t emS e l e cted ( ) onNothing S e l e cted ( ) ,


Adapte r\7 i ew . On i t emS e l e ctedL i s t ene r .


C reate New Project :
Proj ect name -

Spinne rApp;

Application name Package name

Spinne r S amp l e ;

- .

Create Activity -

s amp l e s . spinne r ;

Sp inne rAc t i v i t y .

7.7

< ? xml ve r s i on= "

. 0 " encoding= " ut f - 8 " ? >

<Linea rLayout xmlns : andro i d= " http : / / s chema s . andro i d . com/ apk / re s / andro i d "
andro i d : o r i entation= " v e rt i ca l "
andr oid : l ayout_width= " f i l l_pa rent "
andro id : l ayout_he i ght= " f i l l_pa rent "
<TextView
andro i d : id= " @ + id/TextViewO l "

151

-
android : layout_width= " fi l l_parent "
android : layout_he i ght= "wrap_content " / >
< Spinner
android : id= " @ + id/SpinnerO l "
android : layout_width= " f i l l_parent "
android : layout_he i ght="wrap_cont ent "
android : drawSe lectorOnTop= " t rue " />
< /Linea rLayout>


7 . 2 . SpinnerAct ivi ty 7 . 8 .

package com . samp les . sp inne r ;


import com . sample s . spinner . R ;
import android . app . Ac t ivi t y ;
import android . os . Bundle ;
import android . view . View;
import android . widget . AdapterView ;
import android . widget . ArrayAdapt e r ;
import andro id . widget . Spinner ;
import andro id . widget . TextView ;
pu l i c c l a s s Spinne rActivity extends Ac t ivity
implements Adapte rView . OnltemSelectedList ener
TextView mLabe l ;
1 1
final St ring [ ] mContact s
" Jacob Ande rson " 1

"Emily Duncan " 1

"Michae l Ful l e r " 1

"Emma Greenman " 1 " Joshua Har r i s on " 1 "Madi s on Johnson " 1
"Matthew Cotman " 1

"Olivia Lawson " 1

"Michael Honeyman " 1

"Andrew Chapman " 1

" I s abe l l a Jackson " 1 "W i l l iam Patterson" 1

" Jos eph Godwin" 1 " Samantha Bus h " 1

"Ch r i s tophe r Gateman " } ;

@ Ove r ride
pu l i c void onC reate ( Bundle s avedinstance State )
super . onCreate ( s avedi nstanceState ) ;
s etContentView ( R . layout . ma in ) ;

1 52

7
mLabel

( TextView ) findVi ewByid ( R . id . TextVi ewO l ) ;

final Spinner spin

( Spinner ) findViewByid ( R . i d . Spinner O l ) ;

spin . s etOn i ternSelectedLi stener ( thi s ) ;


ArrayAdapt er<St ring> a rrayAdapter

new ArrayAdapter<String> (

thi s , android . R . layout . s irnple_spinne r i tern, rnContacts ) ;


a rrayAdapt er . setDropDownViewResource (
android . R . layout . s irnple_spi nne r_dropdown_i tern) ;
spin . s etAdapt er ( a rrayAdapte r ) ;

pu l i c void on i ternSelected (
Adapte rView< ? > parent , View v,

int pos i t i on , long i d )

mLabel . s etText (rnContacts [ po s i t i on ] ) ;

pul ic void onNothingSe lected (AdapterVi ew< ? > pa rent )


mLabel . s etText ( " " ) ;

Isa bella jackson

Williarn Patterso

. 7.6. Spinner

1 53

.
Spinne r . 7.6.

7 3 3 GridView
.

Gr idView . Gr idView,
TextView,
Lis tVi ew,
, ,
ArrayAdapte r, getView ( ) .
GridView .
,
.
, :
.
auto_fi t, ,
;

android : numColnn s -

android : ve rtical Spacing -

;
android : colnnWidth -

andro i d : numColnn s = " auto_fit " . colnnW idth



spacingW idth -
.

android : s t retchode -

GridView
Ecl i pse
Create New Project :

Proj ect name - GridViewApp;

Application n - Gr idView

Package n - com . samples . gridvi ew;

Create Activity - Gr idViewActi vi ty.

Sample;


7.9.

1 54

< ?xml ve r s i on= " l . O " encoding= " ut f- 8 " ?>


<LinearLayout
xmlns : andro id= "http : / / schemas . android . com/ apk/ re s / android"
android : orientat ion= "vert ical "
andro id : layout_width= " fi l l_pa rent "
android : l ayout_he ight= " f i l l_pa rent " >
<TextView
android : id= " @ +id/ labe l "
android : layout_width= " fi l l_pa rent "
android : layout_hei ght=1'wrap_content " / >
<Gr idView
andro id : id= " @ +id/grid"
android : layout_width= " fi l l_pa rent "
android : layout_he ight= " fi l l_pa rent"
android : ve rtical Spacing= " 3 5px "
android : hori zontal Spac ing= " 5px "
andro i d : numColumns = " auto f i t "
android : columnWidth= " l OOpx "
android : s t ret chode= " columnWidth"
android : gravity= " cent e r " / >
< / Linea rLayout>

-
7 . 1 .

DataAdapter,

package com . samples , gridview;


import android . content . Context ;
import andro id . view . View ;
import android . view . ViewGroup ;
import andro id . widget . ArrayAdapt e r ;
import andro id . widget . TextView;
pulic class DataAdapt er extends ArrayAdapter<St ring>
{

private s t a t i c final S t r ing [ ] mContacts


" J . Anderson " , " . Duncan " ,
" .

Greenman " ,

" . Ful l e r " ,

" J . Har r i s on " , " . Johnson " ,

ArrayAdapter,

1 55

-
" . Cotman " ,

" 0 . Lawson " , " . Chapman" ,

" . Honeyman " ,


" J . Godwin " ,

Jackson" ,

"I .

" S . Bush " ,

"W .

Patterson " ,

" . Gateman" ,

" J . Anderson " ,

" .

" . Greenman " ,

" J . Harrison " , " . Johnson " ,

" . Cotman " ,

" .

" . Honeyman " ,

Duncan " ,

" . Ful l er " ,

Lawson " , " . Chapman " ,


Jackson " ,

"I .

" J . Godwin" , " S . Bush " ,

"W .

Patterson " ,

" . Gateman " } ;

Context mContext ;
DataAdapter ( Context context ,

int resource )

s upe r ( context , resourc e , mContacts } ;


this . mContext

context ;

pul ic View getVi ew (


int pos i t i on, View conve rtVi ew , ViewGroup pa rent )
TextView labe l

( TextView) conve rtView ;

i f ( conve rtView == nul l )


convertView
label

new TextView (mContext } ;

( T extView } conve rtVi ew;

labe l . s etText (mContacts [ position ] } ;


return ( conve rtView } ;
1 1
pul ic S t r ing Get i t em ( int po s i t ion }
return mContact s [ pos i t i on ] ;

GridVi ewActivity 7 . 1 1 .
, GridView ,
:
setAdapter ( 1 ,
s etOni temSelectedLi s t ene r ( } ,
oni t emSelected ( ) onNothingSe lected ( } .

package com . samples . g ridvi ew;


import android . app . Activi t y ;
import android . o s . Bundle ;

1 56

import android . view . View ;


impo rt android . widget . AdapterView ;
import android . widget . GridView ;
import andro id . widget . TextView ;

pu l i c c l a s s GridVi ewActivity extends Ac tivity


implements Adapte rView . On i t emS e l ectedListener
pr ivate TextVi ew mSelectText ;
pr ivate DataAdapte r mAdapte r ;
@ Ove rride
pu l i c vo id onCreate ( Bundle s avedins tance Stat e )
s upe r . onCreate ( savedinst ance State ) ;
s etCont entView ( R . layout . mai n ) ;
mS e l ectText= ( TextVi ew ) findVi ewByid ( R . i d . l abe l ) ;

final Gr idView g
mAdapte r

( G r idView ) findVi ewByid ( R . id . g r i d ) ;

new DataAdapte r ( getApp l i cat ionContext ( ) ,

android . R . layout . s imp l e l i s t item l ) ;


_
_
_
g . s etAdapt e r (mAdapte r ) ;
g . s etOn i t emS e l ectedLi stener ( th i s ) ;

@ Ove rride
pu l i c void oni t emS e l ected (AdapterView< ? > parent , View v ,
int pos it ion,
mSe l e c tText . s e tText ( " S e l e cted items :

l ong i d )

+
mAdapt e r . Get item ( p o s i t i on ) ) ;

@ Ove r ride
pu l i c vo id onNothing S e lected (AdapterView< ? > parent )
mS e l ectText . s etText ( " S e l ected items : none " ) ;

.

(. 7. 7).

157

'
. 7.7. GridView

7 4
.

Android
. , -
.
GridView
- G a l l e ry S l idingDrawer.

7.4. 1 . GridView
GridView n .
( - )
, .
n GridView
Ecl i pse n Create
New Proj ect :

Proj ect name - GridViewimageApp;

Application name - Grid'l iew

Package name -

C reate Activity - GridVi ewAct ivity.

with Image Sample;

com . sampl es . grid'Ji ew;

1 58

,
GridView ,
7.9.

a seAdapter. ,
.

ArrayAdapte r<T> .

, res/drawaie/.
photo l .j pg ... photo8.j pg
Resources/Images/ .


New 1 Class. New
Java Class. Name , ImageAdapter,
Finish (. 7 . 8).

Java Class
dfi The use of the default package is discouraged.

.......... :...................... :..:.:............ ............. ... .................. "'

- : :. : .

::: :

L._P.?.y-w-ag!c

. .

. 7.8.

1 59


7. 1 2 .

IrnageAdapte r

package com . samples . g ridvi ewimage ;


import android . content . Context ;
import android . vi ew . View ;
import android . view . Vi ewGroup ;
impo rt android . widget . BaseAdapte r ;
import android . widget . GridView ;
import android . widget . IrnageView;
pu l i c class ImageAdapter extends BaseAdapter
pr ivate Context mContext ;
private static final Integer [ ] mimages
R . drawale . photol , R . drawale . photo2 ,
R . drawale . photo , R . drawale . photo4 ,
R . drawale . photo5 , R . drawale . photo ,
R . drawale . photo7 , R . drawale . photo8 ,
R . drawale . photol , R . drawale . photo2 ,
R . drawal e . photo , R . drawale . photo 4 ,
R . drawal e . photo5 , R . drawale . phot o ,
R . drawal e . photo7 , R . drawale . photo8 ,
R . drawale . photol , R . drawale . photo2 ,
R . drawal e . photo , R . drawale . photo4 ,
R . drawal e . photo 5 , R . drawale . photo ,
R . drawale . photo7 , R . drawale . photo8

pu l i c IrnageAdapte r ( Context context )


mContext

context ;

pu l i c int getCount ( )
return mimage s . length ;

pu l i c Obj ect get item ( int po s i t ion )


return mirnages [ pos i t i on ] ;

1 60

7
pu l i c long get i temid ( int po s i t i on )
return mimage s [ po s i t ion] ;

ImageView

pu l i c View getView (
int po s i t ion, View conve rtView, Vi ewG roup parent )
ImageView view ;
i f ( convertView
view

nul l )

new ImageView (mContext ) ;

view . s et LayoutPa rams ( new Gr idView . LayoutPa rams ( 8 5 , 8 5 ) ) ;


view . s etSca leType ( ImageView . S caleType . CENTER_CROP ) ;
view . s etPadding ( 2 , 2 , 2 , 2 ) ;
else
view

( ImageView ) conve rtView ;

view . s e t imageRe source (mimages [ po s i t i on ] ) ;


return view ;

. 7.9.

GridVi ew,

161

(.
7. 1 1 ), onCreate ( ) :
Adapter

new IrnageAdapte r ( getApplicationContext ( ) ) ;

;rid . s etAdapter (mAdapt e r ) ;

, .

(. 7.9).

7 4 2 Gallery
.

Ga l le r y - ,
.

D-pad . Ga l l e ry
.
,
.1 .
Gallery
Create New Project :

Proj ect name - Gal leryApp;

Application name - CheckedTextView

Package name - . sample s . gallery;

Create Activity - Galle ryAct ivity.

Sample;


7. 1 3 .

<?xml ve r s i on= " l . O " encoding= " ut f - 8 " ? >


<Linea rLayout xmlns : andro id= " http : / / schernas . android . com/apk/re s /andro id"
android : orientat ion= " vertica l "
android : layout_width= " f i l l_pa rent "
andro id : layout_he i ght= " fi l l_parent "
android : gravi ty= " center " >
<Ga l l ery
android : id= " @ +id/ga l l e r y "
androi d : layout_width= " fi l l_parent "
andro id : layout_he ight= "wrap_content " / >

1 62
<TextView
android : id= " @ +id/ text "
android : layout_width= "wrap_content "
android : layout_he ight= "wrap_content "
android : textS t yle= "bold"
android : text S i z e= " 2 4 px " / >
< / Linea rLayout>

- ImageAdapter 7. 1 4.
GridView Ga l l e ry
getView ( ) , .

package com . sample s . gal lery ;


import andro id . content . Context ;
import andro id . view . View;
impo rt android . view . ViewGroup ;
import andro id . widget . BaseAdapte r ;
import android . widget . Ga l l e r y ;
import android . widget . ImageView ;
pu l i c c l a s s ImageAdapter extends BaseAdapter
private int mGa l l e ryitemackg round ;
pr ivate Context mContext ;
private fina l Integer [ ] mimage
R . drawale . photol , R . drawale . photo2 ,
R . drawal e . photo , R . drawale . photo4 ,
R . drawale . photo S , R . drawale . phot o ,
R . drawale . photo7 , R . drawale . photo 8 ,

pu l i c ImageAdapte r ( Context )
mContext

pu l i c View getVi ew (
int pos i t ion, View conve rtVi ew , ViewGroup parent )
ImageView view = new ImageView (mContext ) ;

1 63

-
view . s e t imageResource (mimage [position] ) ;
view . s e t Padding ( 2 0 , 2 0 , 2 0 , 2 0 ) ;
view . set LayoutParams ( new Ga l lery . LayoutParams ( l 4 0 , 1 9 0 ) ) ;
view . setSca leType ( ImageVi ew . ScaleType . FIT_XY ) ;
view . setBackgroundResource ( mGa l leryi temac kground ) ;
return view ;

pu l i c int getCount ( )

return mimage . lengt h ;

pu l i c Obj ect get i tem ( int po s it i on )


return mimage [ pos i t i on ] ;

pu l i c long get i temid ( int pos i t i on )


return mimage [ pos i t i on ] ;

Gal l eryActivity

7 . 1 5 .

package com . sample s . gallery;


import android . app . Activi t y ;
import android . o s . Bundle ;
import andro id . view . View ;
import andro id . widget . AdapterView ;
impo rt android . widget . Ga l l e r y ;
import android . widget . TextView ;
import android . widget . AdapterView . OnitemCl i c kListener ;
pu l i c c l a s s Ga l l e ryActivity extends Act ivity
@ Ove rride
pu l i c vo id onCreate ( Bundle savedins tanceStat e )
supe r . onCreate ( savedinstanceState ) ;
setContentView ( R . layout . main ) ;
fina l Ga l l e ry g

( Ga l lery)

findViewByid ( R . id . ga l l e ry ) ;

g . setAdapt e r ( new ImageAdapte r ( this ) ) ;

1 64
final TextView labe l

( TextView ) findViewByid ( R . id . text ) ;

labe l . s etText ( " S l i de 1 from

+ g . getAdapte r ( ) . getCount ( ) ) ;

g . setOn i t emC l i ckL i s tener ( new Oni temCl i ckLis tener ( )


pu ic void onitemCl ick (Adapte rView< ? > parent ,
View

v,

int pos , long id)

label . s etText (
" S l ide

+ ++pos

f rom

+ pa rent . ge tCount ( ) ) ;

.
<
,
. 7 . 1 .

. 7. 1 0 . Ga l l e ry

7 4 3 SlidingDrawer
.

S l i d i ng Drawe r - .
Application Launcher,
, ( . . 2 .9).

t-

1 65

S l i dingDrawe r
.
. S l i dingDrawe r .

: , ,
,
.

S l i dingDrawe r ,
S l idingDrawe r.
f i l l_pa rent .
L- S l idingDrawe r
( )
.
S l idingDrawe r
. S l idingDrawe r ,
- ,
.
, .
L- S l idingDrawe r
:
android : handle= " @ + id/handl e "
android : content= " @ +id/content "

S l idingDrawe r
Ecl ipse C reate New Project
:
D Project name -

S l i dingDrawe rApp;

D Application name -

S l idingDrawe r Sample;

D Package name - com . sampl es . s l idingdrawe r;


D C reate Activity - S l idingDrawe rActivity.


, . 7. 4. 1 .
Resources/Images/
. , ,
Android SDK.
GridView


7 . 1 6 .

1 66

<?xml ve rs i on= " l . O " encoding= " ut f- 8 " ?>


<LinearLayout
xrnlns : andro id= "http : / / schemas . android . com/apk/ res /andro id"
android : orientat i on= " ve r t i ca l "
andro id : layout_width= " f i l l_pa rent "
android : layout_he ight= " fi l l_pa rent " >
<TextView
android : i d= " @ +id/ label "
android : layout_wi dth= " fi l l_parent "
androi d : l ayout_he ight="wrap_content " />
< S l i dingDrawer
android : id= " @ + id/drawe r "
android : layout_width= " f i l l_parent "
android : layout_he ight= " f i l l_pa rent "
android : handl e= " @ + i d/handle "
android : content= " @ + id/ content "
androi d : bottom0ffset=" 9px " >
< ImageView
android : id= " @ id/handle"
android : layout_width= " 3 2 0dip"
android : layout_he ight= " 5 0dip"
android : s rc= " @ drawale/handle " / >
<LinearLayout
android : id= " @ id/content "
android : orientation= " vertica l "
android : layout_width= " f i l l_parent "
android : layout_he ight= " f i l l_parent " >
<GridView
andro i d : id= " @ + id/grid"
android : layout width= " f i l l_pa rent "
android : layout_he ight= " f i l l_parent "
android : numCo lumns= " auto f i t "
android : ve rtical Spacing= " l Odp "
android : ho r i z ontal Spacing= " l O dp "
andro id : columnWidth= " Odp "
andro id : stretchode= " co lumnWidth"
android : gravity= " cente r " />

167

< /LinearLayout>
< / S l idingDrawe r>
< / Linea rLayout>

S l idingDrawe rActivity
GridView 7 . 1 7 .

package com . samples . s l idingdrave r ;


import android . app . Ac t ivi t y ;
import andro id . os . Bundle ;
import andro id . view . View;
import android . widget . AdapterView ;
import andro id . widget . GridView ;
import andro id . widget . TextView ;
pu l i c c l a s s S l idingDrawe rActivity extends Act ivi t y
implements AdapterView . OnitemSelectedLi stener {
pr ivate TextView mSel ectText ;
pr ivate ImageAdapter mAdapt e r ;
@ Ove rride
pu ic void onCreate ( Bundle savedinstance State )
super . onCreate ( savedins tanceStat e ) ;
setContentView ( R . l ayout . ma in ) ;
mSelectText= ( TextView ) findViewByid ( R . i d . labe l ) ;
GridView gridview
mAdapt e r

( GridView ) findViewByid ( R . id . grid) ;

new ImageAdapter ( th i s ) ;

gridview . s etAdapt e r (mAdapte r ) ;


gridview . s etOni temSel ectedLi stene r ( thi s ) ;

@ Override
pu l i c void oni temSel ected (Adapte rView< ? > parent ,
View v,

int pos i t i on , long id)

mSelectText . s etText ( " S elected i t ems I D :


mAdapt e r . geti temid ( pos i t i on ) ) ;

1 68
@ Override
pul i c void onNothingS elected ( Adapte rView< ?> parent )
mSe l ectText . s etText ( " Sel ected items : none " ) ;

- ImageAdapt er
,
.
7 . 1 8 .

package com . samples . s l idingdrave r ;


import android . content . Context ;
import android . view . View ;
import andro id . view . ViewGroup ;
import android . widget . Bas eAdapte r ;
import android . widge t . GridView ;
import android . widget . ImageView ;
pu l i c c l a s s ImageAdapter extends BaseAdapter
private Context mContext ;
1 1
private Integer ( ] mimages
R . drawale . ic_launcher_allhide ,
R . drawale . ic_launche r_android,
R . drawale . ic_launcher_brows e r ,
R . drawale . ic_launche r_calculator ,
R . drawal e . ic_launche r_cal enda r ,
R . drawale . ic_launche r_came ra ,
R . drawale . ic_launche r_contacts ,
R . drawale . ic_launche r_emai l ,
R . drawale . i c_launche r_ema i l_gene r i c ,
R . drawale . i c_launche r_gal lery,
R . drawale . ic_launcher_goog le_tal k ,
R . drawale . i c_launche r_home ,
R . drawal e . ic_launche r_im,
R . drawale . ic_launcher_maps ,

1 69

R . drawale . ic_launche r_mus i cplayer_2 ,


R . drawale . ic_launcher_phone_dialer } ;
pul ic ImageAdapte r ( Context )
mContext

pul i c View getView ( int pos i t ion ,


View convertView, Vi ewGroup parent )
ImageView imageView ;
i f ( convertView
imageView

==

nul l )

new ImageView (mContext ) ;

imageView . setLayoutPa rams ( new GridView . LayoutParams ( 8 5 , 8 5 ) ) ;


imageView . setScaleType ( ImageView . S caleType . CENTER_CROP ) ;
imageView . s etPadding ( 8 , 8 , 8 , 8 ) ;
else
imageView

( ImageView ) conve rtVi ew ;

imageView . set imageResource (mimages [ pos i t i on ] ) ;


return imageView ;

pul i c i n t getCount ( )
return mimages . length ;

pu i c Obj ect geti tem ( int pos i t i on )


return nul l ;

pu l i c long get i t emid ( int pos ition )


return ;

. ,
. S l i dingorawe r

(. 7. 1 1 )
.

1 70

. 7.1 1 . S l i dingDrawer

7 5

.

- ,
.
,
.
S impl eAdapter S impleCurs orAdapter.


, L-. :
S impl eAdapte r -

S impleAdapte r ( Context context , L i s t < ? extends Map< St ring , ? > > dat a ,
int resource , S t ring [ ]

from, int [ ] t o )
..

, , ,
: -,
- , - .
ArrayLi s t .
S implecursorAdapt e r
. 15.

1 71

,
. C reate New
Project :
Project name - Lis tContact;
Application name - Contacts Sample;
Package name -

. samples . l is tcontact;

C reate Activity - L i stContactActivity.

, ,
: Name Phone
.

7. 1 9 .

TextView,

< ? xml ve r s i on= " . 0 " encoding= " ut f- 8 " ? >


<Re lat iveLayout
xmlns : andro id= " http : / / s chemas . android . com/apk/ res /andro id"
android : orienta tion=" ho r i z onta l "
android : layout_width= " f i l l_pa rent "
android : layout_he ight= " fi l l_parent " >
<TextView
android : id= " @ + id/name "
android : layout_width= "wrap_cont ent "
android : layout_he ight= "wrap_content "
android : layout_a l i gnPa rentLe ft= " t rue"
android : textS i ze= " l 8 sp" / >
<TextView
android : id= " @ + id/phone "
androi d : layout_wi dth= " wrap_content "
android : layout_he i ght="wrap_content "
android : layout_a l i gnPa rentRight= " t rue "
android : text S i z e= " 1 8 sp "
android : paddingRight= " l Opx " / >
< /Re lativeLayout>

, ,
contact r t em, sh,
N PHONE -
. 7.20.

1 72

package com . samples . l i s tcontact ;


import j ava . ut i l . Hashap ;
pulic c l a s s Contact i tem extends Hashap<St ring , S t ring>
private static final long serialVers ionU I D
pul i c s t a t i c final S t r ing N
pu l i c stat i c final S t r ing PHONE

lL;

"name " ;
"phone " ;

pu l i c Conta c t item ( St r ing name , String phone )


super ( ) ;
supe r . put ( NAE , name ) ;
supe r . put ( PHONE , phone ) ;

ListContactActivity ArrayLis t
( 7.2 1 ).

package com . sample s . l i s t contact ;


import j ava . ut i l . Ar rayList ;
import android . app . ListActivi t y ;
import andro id . os . Bundle ;
import andro id . widget . ListAdapte r ;
import android . widget . S impleAdapt e r ;
pul i c class L i s tContactActivity extends L i s tAct ivity
@ Ove rride
pu i c void onCreate ( Bundle savedinstance Stat e )
supe r . onCreate ( savedinstanceStat e ) ;
ArrayL i s t<Contact i t em> l i s t

new ArrayLi s t < Contact item> ( ) ;

/ 1

l i s t . add ( new Contactitem ( " Jacob Anderson " ,

" 4 12 4 1 2 4 1 1 " ) ) ;

l i s t . add ( new Contact i t em ( "Emi ly Duncan " , " 1 6 1 8 63 1 8 7 " ) ) ;


l i s t . add ( new Contact i t em ( "Mi chae l Ful l e r " ,
l i s t . add ( new Contact i t em ( " Emma Greenman " ,

" 8 9 6 4 4 3 65 8 " ) ) ;
" 964990543" ) ) ;

l i s t . add ( new Contact i t em ( " Joshua Harrison " , " 7 5 9 2 8 5 0 8 6 " ) ) ;


l i s t . add ( new Contac t i t em ( "Madi son Johnson " , " 9 5 0 2 8 5 7 7 7 " ) ) ;

1 73

-
" 687 699999 " ) ) ;

1 i s t . add ( new Cont a c t i t em ( "Matthew Cotman " ,


1 i s t . add ( new Cont a c t i t em ( " 01 ivia Laws on " ,

" 1 61 8 6 3 1 8 7 " ) ) ;

1 i s t . add ( new Cont a c t i t em ( "Andrew Chapman " ,

"54 6599645" ) ) ;

1 i s t . add ( new Cont a c t i t em ( " Dani e 1 Honeyman " ,

" 8 7 654564 4 " ) ) ;

1 i s t . add ( new Contact i t em ( " I s abe 1 1 a Ja ckson " ,


1 i s t . add ( new Cont a c t i tem ( "W i l l i am Pat t e r s on " ,
1 i s t . add ( new Cont act l t em ( " Jo s eph Godwin" ,
1 i s t . add ( new Cont a c t l t em ( " S amantha Bu s h " ,

" 907868756" ) ) ;
"687699693 " ) ) ;

" 9 654 6757 5 " ) ) ;


" 90 7 8 6564 5 " ) ) ;

1 i s t . add ( new Cont a c t l t em ( " Chri s t ophe r Gateman" ,

" 8 9 68 7 4 55 6 " ) ) ;

L i s tAdapt e r adapt e r
th i s ,

1ist ,

new S t ring [ ]
new int [ ]

new S imp 1 eAdapt e r (


R . 1 a yout . ma i n ,
{ Contact l t em . NAE ,

{ R . i d . name ,

Cont act l t em . PHONE } ,

R . id . phone } ) ;

s e t L i s tAdapte r ( adapte r ) ;

. 7 1 2
.


( 1 1)
( 15) .

. 7. 1 2 .


, .
, ,
.

:

Toast Not i f i ca t i on -

:::J

B a r Not i f i ca t i on - ,

.

,
;
S t atus

8 . 1 .
,
.
.:: , ,

.
.
\ , .

. ,
,
.

Toa s t oa s t . ma keText ( ) , -

1 76

show ( ) ,
:
Context context
Toa s t toa s t

getAppl i ca t i onContext ( ) ;

Toa s t . rna keText ( context ,

" T h i s i s Toa s t No t i f i c a t i on " ,

Toas t . LENGTH SHORT ) ;

toa s t . show ( ) ;

ma keText ( ) :
D ;
D ;
D ,
:

LENGTH_LONG -
.

LENGTH SHORT -


, .

.
s e tG ravi t y ( int , int , i nt ) . :
D
, Grav i t y (,
GRAVITY . CENTER, GRAVITY . .);
D ;
D .

, ,
:
toast . s e tGravi t y ( G rav i t y . CENTER ,

, 0) ;

,
. -
.

C reate New Proj ect :
D Proj ect name - Toas tNot i f i c a t i onApp;
D Application name - Toas tNot i f i ca t i on

Samp l e ;

1 77

Ll Package name -

. sarnples . toastno t i f i cat ion;

Ll C reate Activity - ToastNoti fi cat ionActivity.


8 . 1 .

Button

<?xml ve r s i on= " l . O " encoding= "ut f- 8 " ? >


<Linea rLayout xmlns : android= " http : / / schemas . android . com/apk/ re s / andro id"
android : orient a t i on= "vert i ca l "
andro id : layout_width= " fi l l_pa rent "
andro id : layout_he i ght= " fi l l_pa rent "
<Butt on
android : id= " @ + id/button"
andro id : layout_width= " fi l l_parent "
android : layout_height= "wrap_content "
android : text= " Ca l l Toa s t Not i fication " / >
< / Linea rLayout >

oastAct ivity, , ,
8 . 2 .

package com . sarnple s . toastdialog ;


import android . app . Act ivi t y ;
import android . content . Context ;
import android . os . Bundle ;
import andro id . view . Gravi t y ;
import android . view . View;
import android . widget . Butt on ;
import andro id . widget . Toast ;
'
pul i c c l a s s Toas tAct ivity extends Act ivit y
implements View . OnC l i ckLi stene r {
private Button mutton ;
@ Override
pul i c void onC reate ( Bundle savedi nstance State )
supe r . onCreate ( savedinstance State ) ;

1 78

s e tContentView ( R . l a yout . ma i n ) ;
mutton

( Button ) f indVi ewByid ( R . i d . button ) ;

mut ton . s etOnC l i c k L i s t ene r ( thi s ) ;

pu i c void onCl i c k ( View v i e w )


Context context

ge tApp l i c a t i onContext ( ) ;

Toa s t toas t

Toa s t . ma keText ( context ,

" Th i s i s Toa s t Not i f i ca t i on " ,


toas t . s e tGravi t y ( Grav i t y . CENTER ,

Toa s t . LENGTH SHORT ) ;


_
0) ;

toas t . s how ( ) ;

.

(. 8 . 1 ) .

. 8 . 1 .

1 79

8.2 .


,
.
L-
Layout inflater getLayout inflater ( )
getsys temS e rvice ( ) , Layout inflater. i
inflate ( ) View .
, cus tom_layout . xml
android : id= " @ +id/toa s t la yout "
:
Layoutinflater inflater
View layout

getLayout inflate r ( ) ;

inflater . inflate ( R . layout . cus tom_layout ,

(Vi ewGroup ) findViewByi d ( R . id . toast_layout ) ) ;

inflate ( ) :

custom

la yout . xml ) ;

toast _layout ) .


findViewByid ( )
.
o a s t , ,
, Gravi t y .
Toast toast

new Toa s t ( getApp l i c a t i onContext ( ) ) ;

toast . setGravi t y ( Gravi ty . CENTER_VERT ICAL , , 0 ) ;


toas t . setDurat ion ( Toa s t . LENGTH_LONG ) ;

setView ( ) ,
, show ( ) ,
:
toast . s etView ( layout ) ;
toast . show ( ) ;


Create New Proj ect :

1 80

Project name - Cus tomToa s t ;


Application name - CustomToa s t Sample;
Package name - . sampl e s . cus tomtoa s t ;
Create Activity - CustomToa s tAct ivity.

( . 8. 1 ).

Android Tools 1 New Resource File. New And roid XML File.
File - cus tom_l ayout . xml,
What type of resource would you like to create?
Layout, Folder Select the root element for the XML fille
(. 8.2).

Project L9!mTtiFit;=--

torn)Yct:;rnl .

Aie

What

type

of resourc

would

you bke

to

cr

Ovalues
0i;;!i@
Searchae
reference
Wht type of resouce coofiguration you lil<e?
.

i ;,=ode
li::

"

! 4$ Navigati

... :"') ' .


.

1R
\' i j!i

1
---...................... .

Select the root olement for the

= ::::;

l:J.oimensi

Foider

..

.,. ",".

j d Orientation
! Pixel Density

1 ;::!

(! AppWidget Provlder

i.i<;

vaiahki Quaiflers

l'fct;c;,; .

Q enu
Q Anlmatlon

Fin1sh
. 8.2. L-

1 !' Cancel

181

Finish .
toast_layout.
, IrnageView TextView, 8 .3 .

LinearLayout

<LinearLayout xmlns : android= " http : / / schernas . android . com/ apk/ re s / andro id"
andro id : id= " @+ i d/toast_l ayout "
andro id : orientation= " hori z onta l "
andro id : l ayout_width= " fi l l_pa rent "
andro id : layout_he i ght= " fi l l_pa rent "
android : padding= " l Odp "
android : background= " # DAAA" >
< IrnageView android : id= " @ +id/ irnage "
androi d : l ayout_width= "wrap_content "
androi d : layout_he ight= " f i l l_pa rent "
andro id : l ayout_ma rginRight= " l Odp " / >
<TextView android : id= " @ +id/text "
andro i d : layout_width= "wrap_content "
andro id : layout_he i ght= " fi l l_pa rent "
android : textColor= " # FFF" / >
</LinearLayout >

custom oastAc t ivity


8.4.

package com . sample s . customtoas t ;


import android . app . Ac t ivi t y ;
import android . os . Bundle ;
import android . view . Gravi t y ;
import andro id . view . Layout inflate r ;
import android . view . View ;
import android . view . ViewGroup ;
import andro id . widget . Button ;
import android . widget . IrnageView;
import android . widget . TextView ;
import andro id . widget . Toast ;

1 82
pu i c c l a s s CustomToastActivity extends Activity
implements View . OnC l i ckLi s tener
Button mutton ;
@ Ove rride
pu i c void onCreate ( Bundle s avedi ns tance S tate )
supe r . onCreate ( savedinstance State ) ;
setContentView ( R . layout . ma in ) ;
mut ton= ( Button ) findViewByid ( R . id . button) ;
mut ton . s etOnC l i ckLi s tene r ( thi s ) ;

pu i c void onC l i c k (View view )


Layout i n f l a t e r inflater
View layout

getLayout inflat e r ( ) ;

inflater . inflate ( R . layout . custom_l ayout ,

(ViewGroup ) f indViewBy id ( R . i d . toast layout ) ) ;


ImageView image

( ImageView ) layout . findViewByid ( R . i d . image ) ;

image . s et imageResource ( R . drawa e . androidd ) ;


TextView text

( TextView ) layout . f indViewByid ( R . i d . text ) ;

text . s etText ( " He l l o ! This i s


Toa s t toas t

cus tom toa s t ! " ) ;

n ew Toast ( getApp l i cat ionContext ( ) ) ;

toa s t . s e tG ravi ty ( Gravity . CENTER_VERT I CAL , , 0 ) ;


toa s t . s e t Durat ion ( Toa s t . LENGTH_LONG ) ;
toa s t . s e tView ( layout ) ;
toa s t . show ( ) ;

.

(. 8.3).

8 . 3 .

( ,
, Notifications).
, Adroid I ntent,
. -

1 83

. 8.3.

.1 ,
.
,
\1 - .
.1 ,

, , . .
,
.


, ,
.
1 2 .

,
:
Not i f i cat ion -

, ,
( .);

Not i f i cat ionanager - Adroid,

Not i f i ca t i onana ger

1 84

get Sys temS e rvice ( ) , ,


, not i fy ( ) .


getSystemSe rvice ( ) ,
NOT I FI CA ION_SERVICE,
Context :

Not i f i cat i onanage r

Not i ficationanage r not ifyMgr


(Noti ficat ionanage r ) getS ystemService ( Context . NOT I FI CAT ION_SERVICE ) ;

, Not i f icat ion:


int icon

R . drawale . not i f ication i con ;

Cha rSequence t i c ke rText

"Warning ! " ;
long when
System . cur rentT imeMi l l i s ( ) ;
Not i fi cat ion not i f i cat ion
new Not i fication ( i con , t i c ke rTex t , when ) ;

:
Cha rSequence contentT i t l e
Cha rSequence contentText

" not i fication" ;

"He l l o World ! " ;

rntent :

Context context
getApplicationCont ext ( ) ;
Intent intent
new Intent ( th i s , MyC l a s s . c l a s s ) ;

Pendingintent,
,
:
Pendingintent contentintent

Pending intent . getActivity ( this , , intent , 0 ) ;

Pending intent
:

getAct i vi ty ( )

,
;

( , );

Pending rntent

rntent;

1 4.

Not i f i cat ion setLates tEvent info ( )


,
:

1 85


not i f i cat ion . s etLatestEvent info (
context , contentT i t l e , contentText , content intent ) ;

, Not i fi cat ion


not ify ( ) :

Not i ficationanage r

mNoti ficationanage r . not i fy (NOT I FY_I D , not i f i cation ) ;

NOT I FY
,
.
_


Create New Proj ect
:
Proj ect name - StatusBarNot i ficationApp;
Application name - StatusBarNot i fi cation Sarnple;
Package name - com . s arnpl e s . s tatusbarnot i f i cation;
Create Activity - S tatusBarNo t i f i cationActivity.

8 . 1 ( n


).

StatusBarNot i f i cationActivity ,
, .
St atusBarNot i f i cationActivity 8 . 5 .

pac kage com . sarnple s . s tatusba rnot i f i cation;


import android . app . Activi t y ;
import andro id . app . Not i f i cation;
import andro id . app . No t i f i cationanager ;
import andro id . app . Pendingintent ;
import android . content . Context ;
import android . content . Intent ;
import andro id . o s . Bundle ;
import android . view . View;
import android . widget . Button ;
pulic c l a s s StatusBarNot i ficationActivity extends Act ivi ty
implements View . OnC l i ckLis tener
pr ivate Button mutton ;
pr ivate s t a t i c final int NOT I FY ID

101;

private Not i ficationanage r mNot i fyMg r ;

1 86


@ Ove r ride
pul i c void onCreate ( Bundle savedins tanceState )
supe r . onCreate ( s avedinstance State ) ;
setContentView ( R . layout . rnain ) ;
mNot ifyMgr

( Not i ficationanage r ) get Sys ternS e rvi ce (

Context . NOT I F I CAT I ON_SERVICE ) ;


rnutton= ( Button ) findViewByid ( R . id . button ) ;
rnutton . setOnClickListefie r ( thi s ) ;

pul i c void onC l i c k (View view )


int icon

R . drawale . andro id_happy ;

Cha rSequence t i c ke rText


long when

" He l l o ! " ;

S ystern . currentT irneMi l l i s ( ) ;

Context context

getAppl icationContext ( ) ;

Cha rSequence contentT i t l e


Cha rSequence contentText

"Not i f i cation " ;


"Hi , I arn Android ! " ;

Intent not i fi cation!ntent

new Intent (

thi s , StatusBa rNo t i f i cat ionActivity . c l a s s ) ;


Pending intent content !ntent

Pending intent . getActivi t y (

thi s , , not i f i cat ionintent , 0 ) ;


Not i f i cat ion not i f icat ion

new Not i ficat i on (

icon , t i c kerTex t , when ) ;


not i fi cat ion . setLates tEvent info ( context , contentT i t l e ,
contentText , content ! ntent ) ;
mNot i fyMgr . no t i fy ( NOT I FY_I D , not i f i cation ) ;

.
.
(. 8 .4).
Notifications Clear.
, ,
"No service"
.

187

l'fD( 01 :38

2010 1 3

. 8.4.

8 . 4 .



'v ,
.
,
Notifications, .
s e t La t e s tEvent i n fo ( )

:
contentT i t l e - contentext -
.


, RemoteViews
contentVi ew :
RemoteVi ews cont entV iew
getPacka geName ( ) ,

new RemoteViews (

R . l a yout . cu stom_l a yout ) ;

contentV iew . s e t imageVi ewRe s ource ( R . i d . image ,


contentV i ew . s e t TextVi ewext ( R . i d . text ,

text ) ;

R . drawa e . android d ) ;

1 88

Not i f i cat ion not i fi cat ion


new Not i f ication ( i con , t i c ke rText , when ) ;
not i f icat ion . content !ntent
content !ntent ;
contentView;
not i f i cat ion . contentView
mNoti fyMgr . not i f y ( NOT I FY_I D , not i fication ) ;


Create New Project
:
Project name - CustornStatusBarNot i ficationApp;
Application name - CustornS tatusBarNo t i fication Sarnple;
Package name - corn . s arnp l e s . custorns tatusbarno t i f i cat ion;
C reate Activity - CustomS tatusBa rNot i f i cationAct ivity.

mai .xml 8 . 1 .
custom_layout.xm l , 8.3
.
CustornStatusBarNot i f icat, ionAct ivity
, ,
. cus tornS tatusBarNot i f icat ionAc t ivity
8.6.

package corn . sarnp l e s . cus torns tatusbarnot i f i cation;


irnport
irnport
irnport
irnport
irnport
irnport
irnport
irnport
irnport
irnport

andro id . app . Ac t ivi t y ;


android . app . Not i fication ;
android . app . Not i ficat ionanage r ;
andro id . app . Pending !ntent ;
android . content . Context ;
android . content . Intent ;
android . os . Bundle ;
andro id . view . View;
android . widget . Button ;
android . widget . RernoteViews ;

pul i c c l a s s CustornStatusBarNot i f icationAc t ivity extends Act ivi t y


irnplernents View . OnC l i c kL i stene r
private s t a t i c final int NOT I FY

ID

Oxl O O l ;

private Button mutton ;


private Not i ficationanage r mNot i fyMg r ;

1 89

@ Ove r ride
pul i c void onCreate ( Bundle s avedins tanceState )
supe r . onCreate ( savedinstance Stat e ) ;
setContentView ( R . layout . main ) ;
mNot i fyMgr = ( Not i ficationanage r ) get SystemSe rvi ce (
Context . NOT I FICAT I ON_SERVICE ) ;
mut ton= ( Button ) f indViewByid ( R . id . but t on ) ;
mut ton . setOnC l i ckLi stene r ( thi s ) ;

pu l i c void onCl i c k ( View view )


i nt i con

R . drawae . android_happy ;

Cha rSequence t i cke rText


long when

"Hello ! " ;

Sys tem . currentTimeMi l l i s ( ) ;

Cha rSequence t ext


"Hi , I am Android ! This is cus tom Not i fica t i on . " ;
new Intent (

I ntent not i ficationintent

thi s , Cus tomNot i f i cat ionActivi t y . class ) ;


Pending i ntent content intent

Pendingintent . ge tActivi t y (

thi s , , not i ficat ion!ntent , 0 ) ;


RemoteVi ews contentView = new RemoteViews (
get PackageName ( ) , R . layout . cust om_layout ) ;
contentView . se t imageViewRes ource ( R . id . image ,
R . drawae . andro idd ) ;
contentView . se tTextViewext ( R . id . text , text ) ;
Noti fication not i f icat ion

new Not i fi cation (

icon , t i c kerText , when ) ;


not i fi cat ion . content !ntent
not i fi cation . contentView

content !ntent ;
contentView;

mNot i fyMgr . no t i fy (NO I FY_I D , not i f i cat ion ) ;

.
.
,
(. 8 . 5 ).

1 90

. 8.5.

- ,
. ,
.
,
,
.
Android :
Ale rtDialog - , , -

;
Progre s s Di a l og - ;
Date PickerDialog - ;
T irnePi ckerDialog - .

. 9 . 1 .

Dia log

.
DatePickerDia log -
.

Progre s s Dia log, T irnePi ckerDialog


AlertDialog,

Object

Dialog

AlertDialog

1
1-----1 TimePickerDialog 1
P rogressDialog 1
------,

1-----1 DatePickerDialog

9.1 .

1 92

9 . 1 .

.
oncreateDialog ( ) ,
. Android
( ) ,
.

onCreateDialog ( ) ,
,
. ,
setOWnerAct i vi t ( ) , .

showDialog ( )
(,
), .
:
private s t a t i c final i n t I D D EXIT

showDialog ( I DD_EXIT ) ;

Android

onCreateDia log ( ) . onCreateDialog ( )
, showDialog ( ) .
, .

,
, :
pr ivate s ta t i c final int I D D ALERT

privat e s t a t i c final int I D D_EXIT


onCreateDialog ( ) swi t ch:

showDialog ( )

protected Dia log onCreateDialog ( int id)


Dialog dialog;
swi tch ( i d ) {
case IDD ALERT :
brea k ;
case I D D EXIT :
brea k ;

1 93


de faul t :
dialog

nul l ;

return dialog ;

swi t ch
,
.
Adroid
onPrepa reDia log ( int , Dialog ) .
(,
),
. Dialog,
onCreateDialog ( ) .

9 . 2 . AlertDialog
Ale rt D ialog - Dialog.
.
:
;
;
, ;
;
;
.

9 . 2. 1 . A lertDia/og

Ale r t Dialog
( ) Al ertDialog . Bui lde r:

set . . . But ton

setPosit iveButton ( ) ;
setNegat i veButton ( ) ;
setNeutra lButton ( ) .


n n :
AlertDialog . Bu i lde r bui lder
new AlertDialog . Bu i lde r ( getAppl icat ionContext ( ) ) ;

ui lder,

1 94

, j1 Bui lde r,
,
setMe s sage ( ) :
bui lder . setMe s s age ( "Are you sure you want to exit ? " ) ;


. AlertDialog
: Pos it ive, Negat ive Neut ral, . .
- .
set . . utton ( )

Dia loginterface . onc l ic kLi s tene r, ,
. , Yes
No :
,

bui lde r . s e t Pos i t iveButton ( " Yes " , new D i a l oginterface . OnCl ickLi s tene r ( )
pu l i c void onCl i c k ( Dia loginte rface dialog , int i d )
1 1 rn
AlertDialogButtonActivity . this . finish ( ) ;
}) ;

bui lde r . setNegat iveButton ( "No " , new D i a l oginterface . OnCl i ckLi s t ene r ( )
pu l i c void onCl i c k ( Dia loginterface dialog , int i d )
1 1 m
dialog . cancel ( ) ;

<Back>
, setCance lale ( ) :
bui l de r . setCance lale ( fa l s e ) ;

, :
Alert D i a l og alert

bui l der . create ( ) ;

Create New Proj ect


:
Proj ect name - AlertDial ogButtonApp;
Application name - Alert D i a l ogButton Sample;
Package name - corn . sampl es . ale rtdial ogbutton;
Create Activ ity - Al ertDial ogButtonActi vi t y.

1 95


9 . 1 .

<?xml ve rs i on= " l . O " encoding= " u t f- 8 " ?>


<Linea rLayout xmlns : android= " http : / / schemas . android . com/ apk / re s /andro id"
android : orientation= "vertica l "
android : layout_width= " fi l l_pa rent "
android : layout_he i ght= " fi l l_parent "
<Butt on
android : id= " @ + id/button"
android : text= " Ca l l Ale rtDia log with Buttons "
android : layout _width= " fi l l _parent "
andro id : layout_he ight = " wrap_content " / >
< / LinearLayout>

Ale rtDialogButtonAct ivi t y


, . 9.2.

package com . sample s . a l e rtdialogbutton ;


import android . app . Ac t ivi t y ;
import android . app . Ale rtDialog ;
import android . app . Dialog ;
import android . content . Dialog l nte rface ;
import android . os . Bundle ;
import andro id . view . View;
import android . view . View . OnCl ickLi stene r ;
import android . widget . Button ;
pu l i c c l a s s Ale rtDialogButtonActivity extends Act ivi t y
1 /
private final int IDD EXIT

@ Ove r r i de
pu l i c void onCreate ( Bundle s avedins tance S tate )
supe r . onCreate ( savedi nstance State ) ;
setContentView ( R . layout . main ) ;

1 96

9
final Button cal lButton

( Button ) f indViewByid ( R . id . button ) ;

cal lButton . se tOnC l i c kListener ( new OnCl ickListene r ( )

@ Ove rride
pu l i c void onC l i c k (View v )
1 1
showDialog ( I DD_EXIT ) ;

@ Ove rride
protected Dialog onCreateDia log ( int i d )
swit ch ( id )

case I DD EXIT :
Ale rtDialog . Bu i lder bui lder

new Ale rtDia log . Builde r ( thi s ) ;

bui lder . s etMe s s age ( "Are you sure you want to exit ? " ) ;
1 / "Ye s "
bui lde r . s etPo s i tiveButton (
"Yes " , new Dialoginterface . OnC l i c kLis tener ( )
pu l i c void onCl i c k ( Dialoginte rface dialog , int id)
AlertDialogButtonAc t ivity . this . finish { ) ;
}) ;

1 1 "No "
bui lde r . s e tNegativeButton (
"No" , new Dia loginte rface . OnC l i ckListener ( )
pu l i c void onCl ick ( Dialoginte rface dialog , int id)
dialog . cance l ( ) ;

bui lde r . s etCancelale ( fals e ) ;


return bui lde r . create ( ) ;
defaul t :
return nul l ;

.
AlertDialog Yes No.

197

Yes .
. 9.2.

. 9.2. Al ertDialog Yes N o

9 . 2 . 2 . A lertDialog
Al ertDialog ,
s e t r t ems ( ) ,

Dialogint e r face . OnC l i c kLis tener, ,
, :
Cha rSequence [ ] colors

{ " Red " , " Green " , "Blue " } ;

bui lder . s e t i t ems ( colo r s , new D i a l ogint e r face . OnCl ickLi stener ( )
pu i c vo id onCl i c k ( Dialogint e r face dialog , int i tem )
1 1
Toa s t . ma keText ( getApp l i ca t ionContext ( ) ,
"Color :

+ mColors [ i tem] , Toas t . LENGTH SHORT ) . show ( ) ;


Create New Project :

1 98

Proj ect name - Ale rt D i a l ogLi s tApp;


Application name - Alert Di a l og with L i s t Sample;
Package name - com . samp l e s . a l e rtdialog l i s t ;
Create Activity - Al ertDialogLi s tAct i vi ty.

main.xml 9. 1 .

, . 9.3 .

Ale rtDialogLi s tAct ivi t y

package com . samples . a l e rtdialogl i s t ;


import andro id . app . Ac t ivi t y ;
import android . app . Al e rt D i a l og ;
import andro id . app . D i a l og ;
import andro id . content . Dialoginterface ;
import android . os . Bundle ;
import android . view . View;
import andro id . view . View . OnC l i c kLis tene r ;
import andro id . widget . Button;
import android . widget . Toas t ;
pu i c c l a s s Al e r t D i a l ogLi s tAct ivity extends Act ivity
p r ivate fina l int I DD_COLOR
final Cha rSequence [ ) mColors

;
{ " Red" , "Green" , " Blue "

@ Override
pu i c void onC reate ( Bundle s avedinstance State )
supe r . onCreate ( s avedinstance State ) ;
setContentView ( R . layout . ma in ) ;
final Button cal lButton

( Button ) findViewByid ( R . id . button ) ;


callButton . s e tOnCl ickLis tener ( new OnCl ickLi stene r ( ) {
@Ove rride
pu ic void onC l i c k (View v )
showDi a l og ( I DD_COLOR ) ;

1 99


@ Ove r r i de
protected D i a l o g onCre a t e D i a log ( int i d )
swi t ch

( id )

c a s e I D D COLOR :
Al e r t D i a l og . Bu i l der bui lde r

new Al e r t Di a log . Bu i l de r ( thi s ) ;

bu i l de r . s etT i t l e ( " P i c k color " ) ;


bui l de r . s e t i t ems ( mCo l o r s ,
new D i a l o g i n t e r face . OnCl i c k L i s tene r ( )
pu l i c vo id onCl i c k ( Dialoginte rface d i a l o g ,
Toast . ma keText ( getApp l i cat ionContext ( ) ,
mCo l o r s [ i tem ] ,

return bu i l de r . create ( ) ;
defaul t :
return nul l ;

Pick

"Color :

Toa s t . LENGTH SHORT ) . s how ( ) ;


_

bu i l de r . s e t Cance l ale ( fa l s e ) ;

G)

int i t em)

color

Red
Green
Blue

. 9 . 3. Al e r t D i a log

200

n . n
AlertDi a l og n n
(. 9.3). n n
, .

9 . 2 . 3 . AlertDialog
n n
s e t S ingleCho i c e i tems ( ) .

onCreateDia log ( ) , Android n n


. , n
n .

,

AlertDialog

n n


s e t i t ems ( )

s e t S ingleCho ice i tems ( ) :


Cha rSequence [ ] colors

{ "Red " , "Green " , "Blue " } ;

bu i lde r . s e t S ingl eChoiceitems ( colors , ,


new D i a l oginte rface . OnCl ickListene r ( )
pu l i c void onCl i c k ( Dialoginterface dialog , int i t em)
Toas t . ma keText ( getApp l i cat ionContext ( ) , " Color :

+ mCo lors [ i t em] ,

Toas t . LENGTH_SHORT ) . show ( ) ;

n s e t S i ngl eChoiceitems ( ) -
, -
, n .

, - 1 .


.
, ,
.
.

n n
Create New Proj ect
:
Proj ect name - Ale rtDialogRadioBut tonsApp;
Application name - Alert Dial ogRadi oButtons Sample;

201


Package name - com . sample s . ale rtdialogradiobuttons ;
Create Activity - AlertDialogRadioButtonsActivity.

main .xm l 9. 1 .

, .
9.4.

AlertDialogRadioButtonsActi vi ty

pac kage com . samples . a l ertdialogradiobuttons ;


import android . app . Ac t ivi t y ;
import android . app . AlertDialog ;
import android . app . Dialog ;
import android . content . Dialoginterface ;
import android . os . Bundl e ;
import android . view . View;
import android . view . View . OnCl ickLis tene r ;
import android . widget . Button ;
import android . widget . Toas t ;
pu l i c c l a s s AlertDialogRadioButtonsActivi t y extends Act ivity
private final static int I DD COLOR

private final Cha rSequence [ ] mColors

{ " Red" , " G reen " , "Blue " ) ;

@ Override
pu l i c void onCreate ( Bundle s avedins tance State )
supe r . onCreate ( savedinstance State ) ;
setContentView ( R . layout . main ) ;
f ina l Button callButton

( Button ) f indViewByid ( R . id . button ) ;


cal lButton . setOnC l i c kLis tene r ( new OnCl ickLis tene r ( ) {
@Ove rride
pu l i c void onC l i c k ( View v )
showDi alog ( I DD_COLOR ) ;

202

9
@ Ove rride
protected D i a l og onCreateDia l og ( int i d )
switch ( id ) {
case I D D COLOR :
Al e r t D i a l og . Bui lder bui lder
new Al ertDia log . Bu i l der ( thi s ) ;
bu i lde r . s etT i t l e ( " Pi c k color'
bu i l de r . s etS ingleChoicei tems (mColors , ,
new D i a log interface . OnC l i c kL i s tene r ( )
pu ic vo id onCl i c k ( Di a l oginterface d i a l og , int item)
Toast . ma keText ( getAppl icationContext ( ) , "Color :
mColors [ i tem] , Toa st . LENGTH_SHORT ) . s how ( ) ;

bui lde r . s etCance lale ( fa l s e ) ;


return bu i l der . create ( ) ;
defaul t :
return nul l ;

.
AlertDi a l og .

Green
B l ue

. 9.4. AlertDialog

203

,
(. 9.4).

9 . 2.4. AlertDialog

setS ingl eCho icertems ( ) .

onC reateDia l og ( ) , Android .


,
.

, s e t S ingl eCho ic e r tems ( )
setMul t iChoiceitems ( ) :
Cha rSequence [ ] colors

{ " Red " , " Green" ,

final boo lean [ ] mChec keditems

{ t rue ,

"Blue " } ;

fa l s e , fa l s e } ;

builde r . s etMu l t iCho i c e i tems ( colors , checkeditems ,


new Dia logint e r face . Onul t iCho iceC l i ckLi stener ( )
@ Ove rride
pu ic vo id onCl i c k ( D i a l o g int e r face dialog , int which , .
boo lean i s Checked )
mCheckeditems [ which ]

i s Checked ;

setMu l t i Choice rtems ( ) -


, -
.


, ,
.


Create New Project :
D Proj ect name - Al ertDial ogChec kBoxesApp;
D Application name - Al ertDial ogChec kBoxes S ample;
D Package name - . samp l e s . a l e rtdial ogche ckboxe s ;
D C reate Activity - Al ertDi a l ogChec kBoxesActi v i ty.

main.xml

9 . 1 .
AlertDia logCheckBoxesActivity

204

, . ,
, 9. 5 .

package com . samples . a lertdialogcheckboxes ;


import android . app . Ac t ivi t y ;
import android . app . Al e rtDia log ;
import android . app . Dia log ;
import android . content . Dialoginte rface ;
import android . os . Bundle ;
import android . view . View;
import android . view . View . OnCl ickLis tene r ;
import android . widget . Button ;
import android . widget . Toas t ;
pu l i c c l a s s Al ertDialogCheckBoxesActivity extends Act ivity
private fina l static int I DD_COLOR

final Cha r S quence [ ] mColors

" Red " ,

final boolean [ ] mChec kedi tems

{ t rue , false , fa l s e ) ;

"Green " , "Blue " ) ;

@ Ove r ride
pul i c voi d onC reate ( Bundle savedinstance State )
super . onCreate ( savedinstance State ) ;
setContentView ( R . layout . main ) ;
f inal Button callButton

( Button ) f indViewByid ( R . id . button ) ;


cal lButton . s etOnCl ickLis tene r ( new OnC l i c kListene r ( ) {
@ Ove r ride
pu l i c void onCl ick ( View v )
showDialog ( I DD_COLOR ) ;

@ Ove rride
protected Dialog onCreate D i a l og ( int i d )
s.w i tch ( id )

case I DD COLOR :

205


Al ertDialog . Bui lde r bui l der

new AlertDia log . Bui lder ( thi s ) ;

builde r . s e tT i t l e ( " Pi c k color " ) ;


bui lde r . s etMult iChoiceitems (mColors , mChe ckedi tems ,
new Dialoginterface . Onul t iChoi ceC l i c kLi stene r ( )
@Ove rride
pu l i c void onCl ick ( Dialoginte r face dialog ,
boolean i sChecked ) {
mCheckeditems [ which ]

int which,

i s Checked ;

bui l de r . s etPo s i tiveBut ton (


"Yes " , new Dialogin t. erface . OnC l i c kL i s tener ( )
pu l i c void onCl ick ( Dialoginte rface dialog , int i d )
S t r ingBui lde r s tate
new StringBuilder ( ) ;
for ( int i

; i < mColors . length ; i++ )


+ mColors [ i ] +

state . append ( "Color :

s tate :

i f (mChec keditems [ i ] )
s tate . append ( " checked\n " ) ;
else
s tate . append ( "unchecked\n" ) ;
Toas t . ma keText ( getApp l i ca t ionContext ( ) ,
s tate . toString ( ) , Toas t . LENGTH_LONG ) . show ( ) ;

builde r . s etNegativeButton (
"No" , new Dialog interface . OnCl ickLis tene r ( )
pu l i c void onCl ick ( Dialoginterface dialog, int i d )
dialog . cance l ( ) ;
Toas t . ma keText ( getApp l i cationContext ( ) ,
" Di a l og cancel " , Toas t . LENGTH_SHORT ) . show ( ) ;

bui lde r . s etCance lale ( fa l s e ) ;


return bui l de r . create ( ) ;
defaul t :
return nul l ;

206

n n n . n
n A l e r t D i a l og n
(. 9 . 5 ) . n Yes n n
, n .

Blue
color:

Blue,

state: checked

. 9.5. Al e r t D i a l og

9 . 3 . ProgressDialog
Progre s s D i a log - n Al e r t D i a log, n
n. n
n, n n .

Prog re s s D i a log

Progre s s D i a l og ( Context ) , n n
:
Progre s s D i a l og progre s s D i a l og

new Progre s s Di a log ( Ac t iv i t y_Name . thi s ) ;

, n:
progre s s D i a l og . s et Progre s s S t y l e ( Progre s s Di a l og . STYLE_HOR I Z ONTAL ) ;
progre s s Di a log . s etMe s s a ge ( " Loading .
progre s s D i a l og . s e t Cance lale ( fa l s e ) ;

207

, . .

, Handler
( 5):
Handler handler

new Handler ( )

pul ic void handleMe s s age ( Mes sage ms g )


progre s s Di a l og . s et Prog res s ( tota l ) ;

,
, Ecl ipse
Create New Project :
L] Proj ect name - Progre s s D i a l ogApp;
L] Application name - Progre s s Di a l og Sample;
Package name - com . samples . progre s sdia log;

L] C rea te Activity - Progre s s D i a l ogAct ivity.

9 . 1 .

, .
Se condThread,
onCreateDia log ( ) .

Progre s s DialogActivity

Progre s s Dia logAc t ivity,


, 9 . 6 . SecondThread
- 9 . 7

package com . samp l e s . progres sdia l og ;


import andro id . app . Act ivi t y ;
import andro id . app . Di a l og ;
import andro id . app . Progre s s Di a l og ;
import andro id . o s . Bundle ;
import andro id . os . Handl e r ;
import andro id . os . Me s s age ;
import android . view . View ;

208

import android . view . Vi ew . OnC l i ckL i s tene r ;


import android . widget . Button ;
import andro id . widget . Toas t ;
pu i c c l a s s Progre s s DialogActivity extends Activity
static final int I DD PROGRE S S

pr ivate SecondThread mSecondThread ;


private Progre s s Dialog mProgre s s Dialog;
pu l i c void onCreate ( Bundle s avedins tance S tate )
supe r . onCreate ( savedinstanceState ) ;
setContentView ( R . layout . ma i n ) ;
final Button callButton

( Button ) f indViewByid ( R . id . button ) ;

callButton . setOnC l i ckLi s tene r ( new OnC l i ckLi stene r ( ) {


pu l i c vo id onCl i c k ( View v )

showDialog ( I DD_PROGRE S S ) ;

rotected Dialog onCreateDialog ( int id)


swi t ch ( id)

case I DD PROGRE S S :
mProgre s s Dialog

new Prog re s s Dialog (

P rogre s s DialogActivity . thi s ) ;


mProgre s s Dialog . s e t Progres s Style (
Progre s s Dialog . STYLE_HORI ZONTAL ) ;
mProgress Dialog . s etMe s s age ( " Loading . Please wai t . . . " ) ;
mSecondThread

new SecondThread ( handler ) ;

mSecondThread . s tart ( ) ;
return mProgre s s Dialog;
defaul t :
return nul l ;

1 1 ,
1 1
final Handle r handler

new Handle r ( )

pu l i c void handleMe s s age (Mess age msg )


int total

msg . getData ( ) . get int ( "Total " ) ;

209


rnProgre s s Dia log . s et Progres s ( total ) ;
i f ( total >= 1 0 0 ) {
di srni s s Dia1og ( I DD_PROGRES S ) ;
rnSecondThread . set State ( SecondThread . STATE_DONE ) ;

Toast . rnakeText ( getApplicationContext ( ) , "Task i s fini shed" ,


Toas t . LENGTH_SHORT ) . show ( ) ;

package corn . sarnples . progre s sdi alog ;


irnport android . os . Bundle ;
irnport android . os . Handle r ;
irnport android . o s . Me s s age ;
irnport android . ut i l . Log ;
pu l i c c l a s s SecondThread extends Thread
Handler rnandl e r ;
final static int STATE DONE

final static int STATE RUNNING

1;

int rnState ;
int rnTotal ;
Se condThread ( Handler hnd )
rnandl e r

hnd ;

pul ic void run ( )

rnState

STATE_RUNN ING ;

rnTotal

whi le (rnState

STATE_RUNN ING )

try {
Thread . s leep ( 1 0 0 ) ;
catch ( I nte rruptedExcept ion )
Log . ( "ERROR" , "Thread Interrupted " ) ;
Mes s age rnsg
Bundle

rnandl e r . obtaine s s age ( ) ;


new Bundle ( ) ;

b . put !nt ( " Total " , rnTotal ) ;

210

rns g . s e t Da t a ( ) ;
rnandl e r . s ende s sage ( rns g ) ;
rnTo t a l + + ;

pul i c void s e t S t a t e ( i n t s tate )


state ;

rnS t a t e

.
,
(. 9 . 6).

. 9 . 6 . Prog re s s D i a l og STYLE_HOR I Z ONTAL

s e t Progre s s S t y l e ( ) .
, Progre s s D i a l og :
0

STYLE_HOR I Z ONTAL;

STYLE SPINNER.

.
9 . 6 s e t Progre s s S t y l e ( ) :
progre s s D i a l og . s e t P rogre s s S t yle ( Prog res s Di a log . STYLE S P INNER ) ;
_

21 1

n n n .
n n Progre s s D i a l og,
, n (. 9 . 7).

. 9 . 7 . Progre s s D i a l og STYLE S P INNER


_

9 . 4 . DatePickerDialog
Da t e P i c ke rD i a l og n n . n
n ,
. , n Ca l enda r n
g e t ( ) Cal enda r n ,
:
C a l enda r
Ye a r
onth
mDay

Cal enda r . ge t i ns t ance ( ) ;

c . ge t ( Ca l e nda r . YEAR ) ;
c . g e t ( Ca l enda r . MONTH ) ;
c . ge t ( Ca l enda r . DAY O F MONTH ) ;
_ _

onCre a t e D i a log ( )
:
a t e P i c k e r D i a l og d i a l og

Da t e P i c ke rD i a l og

new Da t e P i c k e r D i a l o g (

t hi s , rnDa t e S e t L i s tene r , rnYe a r , rnonth , rnDa y ) ;

212

, , -
, -
, ,
.
, -
Date PickerDialog . OnDate setLi s tener,
, , ,
:
private DatePi ckerDia log . OnDateSetListener mDateSetLis tener
new DatePicke rDia l og . OnDateSetListene r ( )
pu l i c void onDateSet ( DatePi cker view ,

int monthOfYe a r , int dayOfMonth )


mYea r

int yea r ,
{

yea r ;

month

monthOfYea r ;

mDay = dayOfonth ;

showDialog ( int dialogid ) .


C reate New Proj ect
:
D Proj ect name - DatePickerDial ogApp;

D Application name - Date P i c kerDia log


D Pa c kage name -

Sample;

. samples . datepicke rdia log;

D C reate Activity - Date PickerDialogAct i vi ty.



9.8.

< ? xml ve rs i on= " l . O " encoding= "utf- 8 " ? >


<Linea rLayout xmlns : android= " http : / / schemas . andro id . com/ apk/ re s / android"
andro id : layout_width= "wrap_content "
android : layout_he ight="wrap_content "
android : orientation= "ve rt ica l " >
<TextView
android : id= " @ +id/text "

213


android : layout_width= "wrap content "
android : layout_he i ght="wrap_content "
android : textS i ze= " 2 8px "
android : textStyle= "bold"
andro id : text= " " / >
<Button
andro id : id=" @ + id/button"
andro id : layout_width= "wrap_content "
andro id : layout_he ight="wrap_conten t "
android : text= " Change t h e date " / >
< / Linea rLayout >

,
9 .9.

pac kage com . sample s . datepicke rdi a log ;


import j ava . ut i l . Calendar ;
import android . app . Activi t y ;
import andro id . app . DatePickerDialog ;
import andro id . app . Dia log ;
import andro id . os . Bundle ;
import android . view . View;
import android . widget . Button;
import android . widget . DatePicke r ;
impo rt android . widget . TextView ;
pulic c l a s s DatePickerDialogActivi t y extends Act ivi t y
private TextView mDateDisplay;
private Button mPi c kDate ;
private int mYear ;
private int mont h ;
private i n t mDay ;
stat i c final i n t I DD DATE

@ Ove rride
protected vo id onCreate ( Bundle savedins tanceState )

DatePickerDia log,

214

9
super o onCreate ( savedins tanceState ) ;
setContentView ( R o layout o main ) ;
( TextView ) findViewByid ( R o id o text ) ;

mDateDisplay

( Button ) f indViewByid ( R o id o button) ;

mPic kDate


mPi c kDate o s etOnCl i c kL i s tene r ( new View o OnC l i ckLis tene r ( )
pu l i c vo id onCl i c k ( View v )
showDialog ( I DD_DATE ) ;

1 1
final Calenda r
mYe ar
month
mDay

Cal endar o getinstance ( ) ;

C o get ( Calenda r o YEAR ) ;


c .. ge t ( Ca l enda r MONTH ) ;

C o get ( Calenda r o DAY_OF_MONTH ) ;


update D i splay ( ) ;

@ Ove r ride
protected D i a l og onCreateDialog ( int id)
swi tch ( id )

case I D D DATE :
return new Date PickerDialog ( th i s ,
mDateSetLis tene r ,
mYea r , month, mDay ) ;
return nul l ;

, TextView
private void updateDisplay ( )
mDateDisplay o setText (
new St ringBui lder ( )
1 1 , 1
o append (month

1 ) o append ( " - " )

append (mDay) append ( " - " )

o append (mYea r ) o append ( " " ) ) ;

215


p r ivate Dat e P i c ke rD i a l og . OnDa t e S et L i s t ener rnDat e S e t L i s tene r
new Dat e P i c ke rD i a l og . OnDa t e S e t L i s tene r ( )
pu l i c void onDa t e S e t ( Da t e P i c k e r v i ew ,
int monthOfYea r ,
mYe a r
month
rnDay

int yea r ,

int dayOfMonth )

yea r ;
monthOfYear ;
dayO fonth ;

upda t e D i s p l a y ( ) ;

.
Da t e P i c ke r D i a l og,
.
.

. 9 . 8 .

. 9.8. Da t e P i c ke r D i a l og

216

9 . 5 . TimePickerDialog
.

DatePi ckerDialog .

T imePi ckerDialog

,
Cal enda r, :
Ca lenda r . get instance ( ) ;
Calendar
mour
c . get ( Ca l enda r . HOUR_OF_DAY ) ;
minute

c . ge t ( Ca l enda r . MINUTE ) ;

oncreateDialog ( )
:
T imePi ckerDialog dialog

TimePi ckerDialog

new T imePickerDi a log (

thi s , timeSetLis tene r , mou r , minute , false ) ;


1 2- (/) - fa l se 24- - t rue.
-
TimePi ckerDialog . OnT imeSetListene r,
:
private T imePickerDi a l og . OnT imeSetLi s tener mTimeSetListene r
new T imePi ckerDialog . OnT imeSetListene r ( )
pu l i c void onT ime Set ( TimePicke r view,
int ourOfDay , int minute )
mour
minute

hourOfDay ;
minute ;


Create New Project
:
LJ Project name - TimePicke r D i a logAct i vi tyApp;
LJ Application name - T ime P i c ke rDia logAct ivity Sample;
LJ Package name - com . samp l e s . t imepicke rdialog;
LJ Create Activity - T imePickerDialogActivity.

9.9 DatePickerDia log.


T imePi ckerDialogAc t ivity 9. 1 .

217

package com . s amp l e s . t imepicke rdi a log ;


import j ava . ut i l . Calenda r ;
import android . app . Act ivi t y ;
import andro id . app . Dia log ;
import android . app . T imePicke rDia log ;
import andro id . os . Bundle ;
import android . view . View;
import android . widget . Button ;
import andro id . widget . TextView ;
import android . widget . TimePicke r ;
pu l i c c l a s s T imePi ckerDialogAct ivi ty extends Act ivi t y
private TextView mTimeDisplay ;
private But ton mPickT ime ;
private int mour ;
private int minut e ;
s t at i c final it I DD I

0;

@ Ove r ride
protected vo id onCreate ( Bundle s avedins tanceState )
supe r . onCreat e ( s avedinstance State ) ;
setContentView ( R . layout . ma in ) ;
mT imeDi splay
mPi c kT ime

( TextView ) findViewByid ( R . i d . tex t ) ;


( Button ) findViewByid ( R . id . but ton ) ;

mPi ckTime . setOnCli ckLi stene r ( new View . OnCl i ckLis tener ( )
pu l i c voi d onC l i c k ( View v )
showDialog ( I DD_T IE ) ;

1 1
final Ca lenda r
mour

Ca lenda r . ge t instance ( ) ;

c . get ( Ca lenda r . HOUR_OF_DAY ) ;

minute = c . get ( Ca l enda r . MINUTE ) ;

218


updateDi splay ( ) ;
@ Override
protected D i a l og onCreateDia log ( int id)
swi t ch ( i d )

case I DD I :
return new T imePicke rDia log (
thi s , mTimeSetLis tene r , mou r , minut e , fa l se ) ;
return nul l ;

ffi TextView
private vo id updateDisplay ( )
mT imeDisplay . s etText (
new S t r ingBu i l der ( )
. append (pad (mRou r ) ) . append ( " : " )
. append ( pad (minute ) ) ) ;

private Time P i c ke rDialog . OnT imeSetListener mTimeSetLi stener


new TimePicke r Dialog . OnT imeSetLi s t ene r ( )
pu l i c void onTimeSet ( TimePi cke r view,
int hourOfDay, int minute )
mour
minute

hourOfDay ;
minute ;

updateDisplay ( ) ;

private s t a t i c S t ring pad ( int )


if ( >= 10)
return S t r ing . va lueOf ( c ) ;
else
return " " + S t r ing . va lueOf ( c ) ;

.
T ime PickerDialog,
.
(. 9.9).

219

. 9.9. T ime P i c kerDialog

9 . 6 .
,
.
n
.

n ,
n

n L-
View n .
Layout inflater.

Layout i n f l a t e r
get Layout inflater ( ) , n n
inflate ( int , ViewGroup ) , n n -
, - n
:
Layout inflater inflater
View l ayout

getLayout inflate r ( ) ;

inflate r . inf late ( R . layout . cus tom_layout ,

(Vi ewGroup ) findViewByid ( R . id . toast layout ) ) ;

n , findViewByid ( )
n -

220

n . n, n
ImageView, :

TextView

TextView text

( T extView ) l ayout . findViewByid ( R . id . text ) ;

text . s etText ( "Are you sure you want to exit ? " ) ;


ImageView image

( ImageView ) l ayout . findVi ewByid ( R . id . image ) ;

image . se t imageRe source ( R . drawale . androidd ) ;

AlertDia log . Bui lde r


n :
Alert D i a l og . Bui l de r builde r

setView ( )

new Ale rtDialog . Bui lde r ( thi s ) ;

bui lde r . s etView ( l ayout ) ;

n
AlertDialog.
n n
n Create New Project :
r:J Project name - Cus tomDialogApp;
r:J Application name - CustomDia log Sample;
r:J Package name -

. s amp l e s . cus tomdialog;

r:J Create Activity - CustomDia logAct ivity.

n
9 . 1 . ,
9 . 1 1 .

<Linea rLayout xmlns : andro id= " http : / / s chema s . android . com/ apk / re s / andro id"
android : id= " @ +id/toa s t_layout "
android : orientat ion= " hori zont a l "
andro id : layout_width= " f i l l_pa rent "
andro id : layout_he i ght= " fi l l_pa rent "
android : padding= " l Odp "
andro id : background= " # DAAA" >
< ImageView android : id= " @ + i d / image"
android : layout_width= " wrap_content "
android : layout_he i ght= " f i l l_pa rent "
android : la yout_ma rg inRight= " l Odp " / >

22 1


<TextView android : id= " @ +id/text "
android : la yout_width= "wrap_content "
android : la yout_he ight= " fi l l_parent "
androi d : textColor= " # FFF" / >
< / L inearLayout >

customDialogAct ivity
, .
Cus tomDialogActivity 9 . 1 2 .

package com . sample s . customdialog ;


import andro id . app . Ac t ivi t y ;
import android . app . Ale rtDia log ;
import andro id . app . Dialog ;
import android . content . Dialoginterface ;
import andro id . os . Bundle ;
import andro id . view . Layout inflate r ;
import android . view . View;
import andro id . view . ViewGroup ;
import andro id . view . View . On C l i ckLi stene r ;
import andro id . widget . But ton ;
import andro id . widget . ImageVi ew;
import andro id . widget . TextView ;
import andro id . widget . Toast ;
pu l i c c l a s s Cus tomDialogActivity extends Act ivity
private final s t a t i c int I DD CUSTOM

0;

@ Ove r ride
pu l i c void onCreate ( Bundle s avedins tance S tate )
supe r . onCreate ( savedinst ance State ) ;
setContentView ( R . layout . main ) ;
final Button cal lButton

( Butt on ) findViewByi d ( R . id . button ) ;


cal lBut ton . setOnC l i ckLi s t ene r ( new OnC l i ckListene r ( ) {
@Override

222

pu l i c void onC l i c k ( View v )


showD i a log ( I DD_CUSTOM ) ;

@ Override
protected Dialog onCreateDia log ( int i d )
swi t ch ( id )

case I DD CUSTOM :
Layout inflater inflater
View layout

get Layout inflate r ( ) ;

inflate r . inflate ( R . layout . custorn_l ayout ,

(ViewGroup ) f indViewByi d ( R . id . toast_layout ) ) ;


TextView t ext

( TextView ) layout . findViewByi d ( R . id . text ) ;

text . s etText ( "Are you sure you want to exit ? " ) ;


IrnageView irnage

( IrnageView ) layout . findViewByid ( R . i d . irnage ) ;

image . s et irnageResource ( R . drawale . android d ) ;


Al ertDia log . Bui lde r bui lder

new Ale rtDialog . Bu i l de r ( thi s ) ;

bui lde r . setView ( l ayout ) ;


bui l de r . s etMe s s age ( " This i s cus t orn dialog ! " ) ;
bui lde r . se t Po s i t iveButton (
" Ye s " , new D i a loginterface . OnCl ickLi s tener ( )
pu l i c vo id onCl ick ( Di a l oginterface dialog , int i d )
CustornDial ogAct ivity . th i s . finish ( ) ;

bui l de r . s etNegat iveButton (


"No " , new Dialoginterface . OnC l i ckLi s t ene r ( )
pu l i c vo id onCl ick ( Dia log i nte rface dialog, int i d )
dia log . cance l ( ) ;
}

bui lde r . s etCance lale ( fa l se ) ;


return bui lder . create ( ) ;
de faul t :
return nul l ;

223

.
A l e r t D i a log Yes No
.
Yes (. 9 . 1 0).

. 9. 1 0 .

10

- . Android

.

Android :
Options ( ) - ,

.
<M EN U> .
:

Icon Menu ( ) - ,
.
. - ,
;
Expanded Menu ( ) -
.
.
More.
Adroid. More
,
;

Context ( ) -

,
( log-press);
S () - ,


. .

1 0

226

1 0 . 1 .
n - n n n
. , , n
<.: <M EN U>.
n, Adroid
onCreateOptionsMenu ( ) , n n enu.
, n
, n enu.
n L- add ( J n
n , n:

private s t a t i c final int I DM OPEN
101;
private s t a t i c final int I DM SAVE

102 ;

pu l i c boolean onC reateOpti onsMenu (Menu menu )


1 1
menu . add ( Menu . NONE , I DM_OPEN , Menu . NONE ,

" Open " ) ;

menu . add ( Menu . NONE , I DM_SAVE , Menu . NONE , " Save " ) ;

add ( J , , :
r:J - n

n ( n n
);
r:J (n

);
r:J n -

. ( enu . NONE )
n ;
r:J - ( -

, ).
enurtem, n
n , n , " "
n n .
onCreateOpt ionsMenu ( ) , n
. n
n , n n
onPrepareOptionsMenu ( ) .

227

, ,
.
enui t em - , .
get i temid ( ) ,
,
, add ( )
onCreateOpt ionsMenu ( ) .
, .
onOpt ions i temS e l ected ( )

:
pu l i c boolean onOpt ions i temS e lected ( Menuitem item )
switch ( item . geti temid ( )
case I DM OPEN :
return t rue ;
case I DM SAVE :
return t rue ;
return false ;

" " (
) , .
" " :
D

s etAlphabe t i cShort cut ( cha r )

s etNume r i cShortcut ( int )

set Short cut ( cha r , int )

- ;

- ;

- .

:
setAlphabe t i cShort cut ( ' q ' ) ;

( <M ENU>)
<q> . (
) ,
.
C reate
New Proj ect :
D Project name - Opt ionsMenuApp;
D Application name - Opt ionsMenu

Sample;

10

228
Package name

. sampl e s . opt ionsmenu;

C reate Activity - Opt i onsMenuAct ivity.


1 0. 1 .

< ?xml ve rs ion= " l . O " encoding= " u t f- 8 " ? >


<LinearLayout xmlns : android= "http : / / schemas . android . com/apk/ re s /andro id"
android : orientation= "ve r t i cal "
android : layout_width= " fi l l_pa rent "
android : la yout_height= " fi l l_pa rent "
android : gravit y= " cente r " >
<TextView
android : layout_width= " fi l l parent "
androi d : layout_he ight = " wrap_content "
androi d : text= " Pre s s ENU button . . . "
android : gravi t y= " cent e r "
android : text S t yl e= "bold" / >
< / LinearLayout>

Opt ionsMenuActivity
, .
Opt ionsMenuActivity 1 0.2.

package com . samples . opt ionsmenu ;


import android . app . Act ivi t y ;
import android . os . Bundl e ;
import android . view . Gravi t y ;
import andro id . view . Menu ;
import android . view . Menui tem;
import android . widget . Toas t ;
pu l i c c l a s s Opt ionsMenuActivity extends Activity
/ 1
pul i c s t a t i c final int I DM OPEN

101;

pul i c s t a t i c final int I DM SAVE

102 ;

pul i c s t a t i c final int I DM EDIT

103 ;

229

pu l i c s t a t i c f ina1 int I DM HELP

104 ;

pu l i c s t a t i c fina 1 int I DM EXIT

105;

@ Ove rride
pu l i c void onCreate ( Bund1e s avedinstanceState )
supe r . onCreate ( s avedinstanceStat e ) ;
set ContentView ( R . 1ayout . main ) ;

@ Ove rride
pu l i c boo1ean onCreateOpt ionsMenu ( Menu menu )

menu . add ( Menu . NONE , I DM_OPEN , Menu . NONE , " Open " )
. s etA1phabeticSho rtcut ( ' o ' ) ;
menu . add ( Menu . NONE , I DM_SAVE , Menu . NONE , " Save " )
. s etA1phabeti cShortcut ( ' s ' ) ;
menu . add ( Menu . NONE , I DM_EDI T , Menu . NONE , "Edit " )
. s etA1phabeticShortcut ( ' e ' ) ;
menu . add ( Menu . NONE , I DM_HELP , Menu . NONE , " 1 " )
. setA1phabet i cShortcut ( ' h ' ) ;
menu . add ( Menu . NONE , I DM_EXI T , Menu . NONE , " Exit " )
. setA1phabet i cShortcut ( ' x ' ) ;
return ( supe r . onCreateOpt ionsMenu (menu ) ) ;

@ Ove rride
pu l i c boo1ean onOpt ions i t emSe1ected ( Menuitem i tem)
Cha rSequence mes s age ;
switch ( item . getitemid ( ) )
case I DM OPEN :
me s sage

" Open item s e 1ected " ;

brea k ;
case I DM SAVE :
me s sage

" Save i tem s e 1ected" ;

bre a k ;
c a s e I DM HELP :
me s sage

"1 i tem s e 1 ected" ;

break ;
case I DM EDIT :
me s sage

"Edit i tem s e 1ected" ;

break ;
case I DM EXIT :
me s sage = "Exit item s e 1ected" ;
brea k ;

230

1 0

de faul t :
return fa l s e ;
Toast toa s t

Toa s t . ma keText ( t hi s , me s s age ,

toa s t . s e tGravi ty ( G ravi ty . CENTER ,

Toa s t . LENGTH_SHORT ) ;

0) ;

toa s t . s how ( ) ;
r e turn t rue ;

. <M ENU>
: Open,
Save, Edit, Help, Exit (. 1 0. 1 ) .

Save

Op<.m

Edlt

Help

EXIt

. 1 0 . 1 .

1 0 . 1 . 1 .
.
s e t i con ( ) . :
menu . add ( Menu . NONE ,

I DM OPEN , Menu . NONE ,


_
. s e t i con ( R . d rawa e . i c menu open ) ;
_
_
menu . add ( Menu . NONE , I DM SAVE , Menu . NONE ,
_
. s e t i con ( R . drawa e . i c menu_s ave ) ;
_

" Open " )


" S ave " )

23 1

, ,
Ecl ipse C reate New Project :
D Proj ect name -

I conenuApp;

D Application name D Package name -

Iconenu Samp1e;

com . samp1es . i conmenu;

D C reate Activity -

I conenuAct ivity.

,
(. 1 0. 1 ) .
CD-ROM, Resources/Menu_Icons/ -
ic_menu_open .png, ic_menu_save.png, ic_menu_edit, ic_menu_help ic_menu_
exit.
Opt ions i conenuActivity, ,
1 0 . 3 .

package com . samp1es . options i conmenu ;


import
import
import
import
import
import

android . app . Ac t ivi t y ;


android . os . Bund1e ;
andro id . view . Grav i t y ;
android . view . Menu ;
android . view . Menui tem;
andro id . widget . Toast ;

pu l i c c 1 a s s Opt ions iconenuActivity extends Act ivi ty


1 1
pu1 i c s t a t i c fina1 int I DM OPEN
101 ;
pu1 i c s t a t i c f ina1 int I DM SAVE
1 02 ;
pu l i c s t a t i c fina1 int I DM EDIT
103 ;
pu1 i c s t a t i c fina1 int I DM HELP
104 ;
pul i c s t a t i c fina1 int I DM EXIT
105;
@ Ove r ride
pu1 i c void onC reate ( Bund1e s avedinstanceState )
supe r . onCreate ( savedinst ance State ) ;
set ContentView ( R . 1ayout . ma in ) ;

@ Ove rride
pu 1 i c boo1ean onCreateOpt ionsMenu ( Menu menu ) {
menu . add ( Menu . NONE , I DM_OPEN , Menu . NONE , " Open " )
. s e t i con ( R . drawal e . i c_menu_open ) ;

1 0

232
menu . add ( Menu . NONE , I DM_SAVE , Menu . NONE , " Save " )
. s e t i con ( R . drawal e . i c_menu_save ) ;
menu . add ( Meu . NONE , I DM_EDIT , Menu . NONE , "Edi t " )
. s e t l con ( R . drawale . i c_menu_edi t ) ;
menu . add ( Menu . NONE , I DM_HELP, Menu . NONE , "Help " )
. s e t l con ( R . drawa le . i c_menu_he lp) ;
menu . add ( Menu . NONE , I DM_EXI T , Menu . NONE , "Exit " )
. s e t i con ( R . drawal e . i c_menu_ex i t ) ;
return ( supe r . onCreateOpt i onsMenu (menu ) ) ;

@ Ove r ride
pu l i c boo l ean onOpt i ons l t emSelected ( Menul tem i tem)
Cha rSequence mes s age ;
'
swi tch ( i tem . g etltemld ( ) )
case I DM OPEN :
"Open i t em se lected" ;
me s s age
brea k ;
cas e I DM SAVE :
me s s age
" Save i t em selected" ;
bre a k ;
case I DM HELP :
me s s age
"Help i t em selected" ;
brea k ;
case I DM EDIT :
"Edit i t em selected" ;
me s s age
brea k ;
case I DM EXIT :
me s s age
"Exit i t em s e l ected " ;
brea k ;
defaul t :
return fa l s e ;
Toa s t . makeText (
Toast toast
thi s , mes s age , Toa st . LENGTH_SHORT ) ;
toas t . setG ravi t y ( G ravi t y . CENTER , , 0 ) ;
toast . s how ( ) ;
return t rue ;

. <MENU>
, ,
, (. 1 0.2).

233

ii
Open

Edit

Sa.re

0
Exlt

. 1 0. 2 .

1 0 . 1 . 2 .
, ,
.
Andro id .

C reate New Proj ect :
D Proj ect name - Opt i onsExpandedenuApp;
D Application name - Opt ionsExpandedenu Sample;
D Package name -

samples . opt i onsexpandedmenu;

D C reate Activity - Opt i onsExpandedenuActivity.

,
(. 1 0 . 1 ) .
, C D-ROM,
Resources/Menu Icons/.
, ,

:
pr ivate s t a t i c final int I DM FIND RE PLACE
106;
pr iva te s t a t i c fina1 int I DM FIND NEXT
107 ;
private s t a t i c fina1 i nt I DM FIND PREV
108 ;
=

234

1 0

onCreateOpt ionsMenu ( ) (
):
pu 1 i c boo1ean onC reateOpt ionsMenu ( Menu menu )
menu . add ( Menu . NONE , I DM_FIND_RE PLACE , Menu . NONE , " Find/Rep1ace " ) ;
menu . add ( Menu . NONE , I DM_FIND_NEXT , Menu . NONE ,

" Find Next " ) ;

menu . add ( Menu . NONE , I DM_FIND_PREV , Menu . NONE ,

" Find P revious " ) ;

return ( supe r . onCreateOpti onsMenu (menu ) ) ;


n n , n
n .

onOpt ions itemSe 1 ected ( )


. Opt ionsExpandedenuActivity
1 0.4.

package com . samp1es . options expandedmenu ;


import android . app . Activi t y ;
import android . os . Bund1e ;
import andro id . view . G ravi t y ;
import android . view . Menu ;
import android . view . Menul tem;
import andro id . widget . Toast ;
pu 1 i c c 1 a s s Opt ionsExpandedenuActivity extends Act ivity
pu l i c s t a t i c fina1 int I DM OPEN

101 ;

pu l i c stat i c fina1 int I DM SAVE

102 ;

pu1 i c s t a t i c fina1 int I DM EDIT

103 ;

pu1 i c stat i c fina1 int I DM HELP

104 ;

pul ic s t a t i c f ina1 int I DM EXIT

105 ;

pu l i c s t a t i c fina1 int I DM FIND REPLACE

106;

pu l i c s t a t i c fina1 int I DM FIND NEXT

107 ;

pu1 ic static f ina1 int I DM FIND PREV

108 ;

@ Ove rride
pu1 ic void onCreate ( Bund1e savedins tanceState )
supe r . onCreate ( savedl nstanceState ) ;

235

set ContentView ( R . l a yout . ma in ) ;

@ Ove rride
pu l i c boo lean onCreateOpt ionsMenu ( Menu menu )
1 1
menu . add ( Menu . NONE , I DM_OPEN , Menu . NONE , " Open " )
. set icon ( R . drawale . ic_menu_open ) ;
menu . add ( Menu . NONE , I DM_SAVE , Menu . NONE , " Save " )
. s et icon ( R . drawale . i c_menu_save ) ;
menu . add ( Menu . NONE , I DM_EDIT , Menu . NONE , "Edi t " )
. s et icon ( R . drawale . i c_menu_edi t ) ;
menu . add ( Menu . NONE , I DM_HELP , Menu . NONE , "Help " )
. s et icon ( R . drawal e . ic_menu_he l p ) ;
menu . add ( Menu . NONE , I DM_EXI T , Menu . NONE , " Exit " )
. s et icon ( R . drawale . i c_menu_ex i t ) ;
. ,
. . _
menu . add ( Menu . NONE , I DM_FIND_REPLACE , Menu . NONE , " Find/Replace " ) ;
menu . add ( Menu . NONE , I DM_FIND_NEXT , Menu . NONE ,

" Find Next " ) ;

menu . add ( Menu . NONE , I DM_FIND_PREV , Menu . NONE ,

" Find Previous " ) ;

return ( supe r . onCreateOpt ionsMenu (menu ) ) ;

@ Ove rride
pu l i c boo lean onOpt ions i t emSe lected ( Menui tem item)
CharSequence mes s age ;
swi t ch ( it em . get i t emi d ( ) )
case I DM OPEN :
me s s age

" Open item selected" ;

brea k ;
c a s e I DM SAVE :
mes s age

" Save i tem s e l ected" ;

break ;
case I DM HELP :
mes sage
brea k ;

" Help item s e l ected" ;

c a s e I DM EDIT :
me s sage

"Edit item s e l ected " ;

brea k ;
ca s e I DM EXIT :
me s s age
bre a k ;

"Exit i tem selected" ;

236

1 0
ca s e I DM FIND RE PLACE :
me s s age

" Find/Replace i t em s e l e c t ed " ;

bre a k ;
c a s e I DM FIND NEXT :
me s s age

" Find Next i t em s e lected " ;

brea k ;
ca s e I DM FIND PREV :
me s s age

" Find Previous i t em s e l e c t ed " ;

break ;
de faul t :
return fa l s e ;
Toa s t toas t

Toa s t . ma keText ( t h i s , me s s age ,

toas t . s e tGravity ( G rav i t y . CENTER ,

Toa s t . LENGTH SHORT ) ;

0) ;

toa s t . s how ( ) ;
return t rue ;

. <M EN U >
n
More . More
(. 1 0 . 3 ) .

Fi nd/Rep lace

11

Find

G>

Find P revious

Open

sav

Exlt

N e xt

Edl t

Mor e

. 1 0. 3 .

237

1 0 . 2 .
Adroid
, .
( \og-press).


(
) .


oncreateContextMenu ( ) .
onCreateContextMenu ( ) ,
add ( ) onContext i temSelected ( ) .
:
pu l i c void onC reateContextMenu ( ContextMenu menu , View v ,
Cont extMenuinfo menuinfo )
supe r . onCreateContextMenu (menu ,

menu info ) ;

menu . add ( Menu . NONE , I DM_OPEN , Menu . NONE , " Open " ) ;
menu . add ( Menu . NONE , I DM_SAVE , Menu . NONE , " Save " ) ;

, ,
.
Menu i tem - , .

, .
onContext i t emS e l ected ( )

pu l i c boolean onContext i t emSel ected ( Menu i t em item)


Cha rSequence mes s age ;
swi tch ( i t em . get i temid ( ) )
ca s e I DM OPEN :
break ;
case I DM SAVE :
break ;
de faul t :
return supe r . onContext i t emS elected ( i tem) ;

238

1 0


C reate New Project :

D Proj ect name - contextMenuApp;


D Application name - ContextMenu
D Package name -

arnple;

sarnple s . contextmenu;

D Create Activity - ContextMenuActivity.



1 0. 5 .

< ?xml ve r s i on= " l . O " encoding= " ut f- 8 " ? >


<Linea rLayout xmlns : androi d= " http : / / s chemas . android . com/ apk / re s / android"
androi d : id= " @ + id/Root "
android : orient a t i on= "ve r t i ca l "
android : la yout_width= " f i l l_pa rent "
andro id : layout_he ight= " fi l l_pa rent "
android : gravi ty= " cente r " >
<TextView
android : la yout_width= "wrap content "
android : layout_he ight="wrap_content "
android : text= " Long-pre s s for ca l l ContextMenu " / >
< /LinearLayout >

ContextMenuActi vity

, 1 0.6.

package com . s arnples . contextmenu ;


import android . app . Activi t y ;
import android . os . Bundle ;
import android . view . ContextMenu ;
import android . view . Gravi t y ;
import android . view . Menu ;
import android . view . Menui tem;
import android . view . View;
import android . view . ContextMenu . ContextMenuinfo ;

239

import android . widget . Linea rLayout ;


import android . widget . Toa s t ;
pu l i c c l a s s ContextMenuAc t ivity extends Activity
pul i c static fina l int I DM OPEN

101 ;

pu l i c s t a t i c fina l int I DM SAVE

102 ;

pu l i c s t a t i c fina l int I DM EDIT

103 ;

pu l i c s t a t i c fina l int I DM HELP

104 ;

pu i c s t a t i c fina l int I DM EXIT

105 ;

@ Ove r r i de
pu i c void onCreate ( Bundle savedins tance State )
super . onCreat e ( savedinstance State ) ;
setContentView ( R . l a yout . ma in ) ;
fina l LinearLayout edi t

( LinearLayout ) f indV i ewByid ( R . id . root ) ;

regi s t e r ForContextMenu ( edi t ) ;

@ Ove r ride
pu l i c voi d onCreateContextMenu ( ContextMenu menu , View v ,
ContextMenuinfo menuinfo )

supe r . onCreateContextMenu (menu , v, menuinfo ) ;


menu . add ( Menu . NONE , I DM_OPEN , Menu . NONE , " Open " ) ;
menu . add ( Menu . NONE , I DM_SAVE , Menu . NONE , " Save " ) ;
menu . add ( Menu . NON E , I DM_E D I T , Menu . NONE , " Edi t " ) ;
menu . add ( Menu . NONE , I DM_HEL P , Menu . NONE ,

" He l p " ) ;

menu . add ( Menu . NONE , I DM_EXI T , Menu . NONE , "Exi t " ) ;

@ Ove r ride
pul i c boolean onContext i t emS e l e cted ( Menuitem i tem)
Cha rSequence mes s age ;
swi t ch ( i tem . get i t emid ( ) )
ca s e I DM OPEN :
mes s age

" Open i t em s e lected" ;

brea k ;
ca s e I DM SAVE :
me s sage

" Save i tem s e lected " ;

brea k ;
ca s e I DM HELP :
rne s sage
brea k ;

"Help item s e l ected " ;

1 0

240
case I DM EDIT :
" Edit item s e lected " ;

me s sage
brea k ;
ca s e I DM EXIT :

" Ex i t item s e l ected " ;

me s s age
brea k ;
de faul t :

return supe r . onContext i t emS elected ( i t em) ;


Toa s t toast

Toa s t . ma keText ( thi s , me s s age , Toas t . LENGTH_SHORT ) ;

toa s t . s etGravi ty ( G ravi ty . CENTER, , 0 ) ;


toa s t . show ( ) ;
return t rue ;

n n n . n
n . 1 0.4.

Edit
H el p
Exit

. 1 0.4.

1 0 . 3 .
, n.
n , n ,

24 1


(File, Edit, View . .).
onCreateOpti onsMenu ( ) ,
.
addSubMenu ( ) ,
SubMenu. SubMenu
, add ( ) . :
pu l i c boolean onCreateOpt ionsMenu ( Menu menu )
SubMenu subMenuFi le

menu . addSubMenu ( " Fi l e " ) ;

subMenuFi le . add ( Menu . NONE , I DM_NEW , Menu . NONE ,

"New" ) ;

subMenuFi le . add ( Menu . NONE , I DM_OPEN , Menu . NONE , " Open " ) ;
subMenuFi le . add ( Menu . NONE , I DM_SAVE , Menu . NONE , " Save " ) ;


C reate New Project :
Proj ect name - suenuApp;
Application name - SubMenu S ample;
Package name - com . samples . sumenu;
Create Activity - SubMenuActivity.

,
1 0 . 1 : File, Edit Help.
:
File - New, Open, Save;
Edit - Cut, , Paste.

suenuActivity

package com . samples . submenu ;


import android . app . Ac t ivity;
import android . os . Bundle ;
import android . view . Gravi t y ;
import android . view . Menu ;
import android . view . Menuitem;
import android . view . SubMenu ;
import andro id . widget . Toa s t ;

1 0.7.

242

1 0

pu l i c c l a s s SubMenuAct ivi t y extends Act ivity


pul ic static final int I DM HELP
pu l i c s t a t i c final int I DM NEW

101 ;
201;

pu l i c stat i c final int I DM OPEN

202 ;

pu l i c s t a t i c final int I DM SAVE

203 ;

pu l i c s t a t i c fina l int I DM CUT


301;
pu l i c s t a t i c fina l int I DM
302 ;
pul i c s t a t i c final int I DM PASTE
303 ;
@ Ove rride
pul i c void onCreate ( Bundle s avedln s tance State )
supe r . onCreate ( savedins tance State ) ;
setContentView ( R . layout . rna in ) ;

@ Ove rride
pul i c boolean onC reateOpti onsMenu ( Menu rnenu )
SuMenu suMenuFi le

rnenu . addSuMenu ( " Fi l e " ) ;

suMenuFi l e . add ( Menu . NONE , I DM_NEW , Menu . NONE , "New" ) ;


suMenuFi l e . add ( Menu . NONE , I DM_OPEN , ' Menu . NONE , " Open " ) ;
suMenuFi le . add ( Menu . NONE , I DM_SAVE , Menu . NONE , " Save " ) ;
SuMenu suMenuEdi t = rnenu . addSubMenu ( "Edi t " ) ;
suMenuEdi t . add ( Menu . NONE , I DM_CUT , Menu . NONE ,

" Cut " ) ;

suMenuEdi t . add (Menu . NONE , I DM_COPY , Menu . NONE , " " ) ;


suMenuEdi t . add (Menu . NONE , I DM_PASTE , Menu . NONE ,
rnenu . add ( Menu . NON E , I DM_HEL P , Menu . NONE , "Help" ) ;
return supe r . onCreateOpt ionsMenu (rnenu ) ;

@ Override
pul i c boo lean onOpt i ons l ternSel ected ( Menultern i tern)
Cha rSequence rnes s age ;
swi tch ( it ern . get l t ernid ( ) )
case I DM NEW :
rne s sage
bre a k ;

"New itern selected" ;

c a s e I DM OPEN :
rne s sage = " Open i t ern s e l ected" ;
bre a k ;

"Paste " ) ;

243

c a s e I DM SAVE :
me s s age

" S ave i t em s e l e c t ed " ;

brea k ;
c a s e I DM CUT :
me s s age

" Cut i t em s e l e c t ed " ;

brea k ;
c a s e I DM :
me s s age

"

i t em s e l e c t ed " ;

brea k ;
c a s e I DM PASTE :
me s s age

" Pa s t e i t em s e l ec t e d " ;

brea k ;
c a s e I DM HEL P :
me s s age

"Help i t em s e l ec t ed " ;

brea k ;
de faul t :
return fa l s e ;

rn

Toa s t toa s t

Toa s t . ma keText ( thi s , me s s age ,

toas t . s e tGravi t y ( Grav i t y . CENTER ,

0) ;

Toa s t . LENGTH SHORT ) ;


_

toa s t . show ( ) ;
return t rue ;

Cut


Paste

. 1 0.5.

1 0

244

. <MENU>
.
File (. 1 0.5). Edit
.

1 0 . 4.


.
,
setCheckae ( )
Menui tern i t ern

rnenu . add ( O , I DM_FORAT_BOL D , , "Bold " )

itern . s etCheckal e ( t rue ) ;


, .
( ).
, add ( ) ,
. .
Color
:
pu i c s t a t i c final int I DM COLOR GROU P
200;
201 ;
pu i c s t a t i c final int I DM COLOR RED
-

202 ;

pu l i c s t a t i c final int I DM COLOR GREEN


-

pu l i c s t a t i c final int I DM COLOR BLUE


-

203;



setGroupCheckal e ( ) .
setCheckale ( ) :
SubMenu suMenuFi l e

rnenu . addSubMenu ( " Col o r " ) ;

suMenuFi le . add ( I DM_COLOR_GROU P , I DM_COLOR_RE D , Menu . NONE , " Red" ) ;


subMenuFi l e . add ( I DM_COLOR_GROU P ,

I DM_COLOR_GREEN , Menu . NONE , "Green" ) ;

subMenuFi le . add ( I DM_COLOR_GROU P , I DM_COLOR_BLUE , Menu . NONE ,

"Blue " ) ;

subMenuFi le . s etGroupCheckale ( I DM_COLOR_GROU P , t rue , fals e ) ;

setGroupCheckale ( )

- ;
- t rue, ;

245

- ( t rue )

( fa lse )

.
- .

. ,
:
pulic boolean onOpt ions i temS e lected (Menuitem item)
switch ( i tem . get i t emid ( ) )
case I DM COLOR RE D :
1 1
item . s etChecked ( ! item . i sChec ked ( ) ) ;
brea k ;


Create New Proj ect :
Proj ect name - Chec kaleSubMenuApp;
Application name - CheckaleSuMenu Sample;
Package name - com . samples . chec kalesubmenu;
Create Activity - Checkal eSubMenuActi vi ty.

main .xml 1 0. 1 .
: Color, Font Style, Help. Color Font Style
. :
Color - Red, Green, Blue;
Font Style - Regular, Bold, Italic.

Chec kaeSuMenuActi vi t y

package com . sample s . checkaesumenu ;


import android . app . Act ivi t y ;
import andro id . os . Bundle ;
import android . view . Gravi t y ;
import android . view . Menu ;
import andro id . view . Menui tem;
import android . view . SubMenu ;
import android . widget . Toa st ;

1 0 . 8 .

246

1 0

pu l i c c l a s s Checkale SuMenuActivi t y extends Act ivi t y


pu l i c s t a t i c final int I DM HELP

101 ;

pu l i c s t a t i c final int I DM COLOR GROUP


pu l i c s t a t i c final int I DM COLOR RE D

200 ;
201;

pul i c s t a t i c final int I DM COLOR GREEN


pul i c s ta t i c final int I DM COLOR BLUE

2 02 ;
203;

pu l i c s t a t i c final int I DM FONT GROUP


pul i c static final int I DM REGULAR
pu l i c s t a t i c final int I DM BOLD
pu l i c s t a t i c final int I DM ITAL I C

300 ;
301 ;

3 02 ;
303;

@ Ove rride
pu i c vo id onC reate ( Bundle savedins tance State )
supe r . onCreate ( savedins tance State ) ;
setContentView ( R . layout . main ) ;

@ Override
pu l i c boolean onCreateOpti onsMenu ( Menu menu )
SuMenu suMenuFi le

menu . addSuMenu ( "Col o r " ) ;

suMenuFi le . add ( I DM_COLOR_GROUP , I DM_COLOR_RED , Menu . NONE , " Red" ) ;


suMenuFile . add ( I DM_COLOR_GROU P , I DM_COLOR_GREEN , Menu . NONE ,
" G reen " ) ;
.
suMenuFi le . add ( I DM_COLOR_GROUP, I DM_COLOR_BLUE , Menu . NONE , "Blue " ) ;
s uMenuFi l e . s e tGroupChec kale ( I DM_COLOR_GROU P , t rue , false ) ;
SuMenu suMenuEdi t

menu . addSuMenu ( " Font Style " ) ;

suMenuEdi t . add ( I DM_FONT_GROUP

I DM_REGULAR , Menu . NONE , " Regular " )

. s etChecked ( t rue ) ;
suMenuEdi t . add ( I DM_FONT_GROUP
suMenuEdi t . add ( I DM_FONT_GROUP

I DM_BOLD , Menu . NONE , "Bold" ) ;

I DM_ITAL C , Menu . NONE , " I ta l i c " ) ;

suMenuEdi t . s etGroupChec kale ( I DM_FONT_GROUP

t rue , t rue ) ;

menu . add ( Menu . NONE , I DM_HEL P , Menu . NONE , "Help" ) ;


return supe r . onCreateOpt ionsMenu (menu ) ;

24 7

@ Ove r ride
pu l i c boolean onOpt ions i t emSel ected (Menu i t em i tem)
CharSequence me s s age ;
swi t ch ( item . get i t emi d ( ) )
case I DM COLOR RED :
item . s etChecked ( ! item . i sChe cked ( ) ) ;
me s sage

" Red i t em selected" ;

break ;
case I DM COLOR GREEN :
i t em . s etChecked ( ! item . i sChecked ( ) ) ;
me s sage

" Green item se lected " ;

bre a k ;
c a s e I DM COLOR BLUE :
item . setChecked ( ! item . i sChe cked ( ) ) ;
me s sage

" Blue item s e l ected " ;

brea k ;
case I DM REGuq :
item . s etChecked ( t rue ) ;
me s sage

" Regul a r item selected" ;

brea k ;
case I DM BOLD :
item . s etChecked ( t rue ) ;
me s sage

" B o l d item se lected " ;

bre a k ;
case I DM ITAL I C :
item . s etChecked ( t rue ) ;
me s sage

" I t a l i c item s e lected" ;

break ;
case I DM HELP :
me s sage

" He lp item selected " ;

break ;
defaul t :
return fa l s e ;
)

1 1
Toa s t toast

Toa s t . makeText ( thi s , me s s age , Toas t . LENGTH_SHORT ) ;

toas t . setGravi t y ( Gravi ty . CENTER, , 0 ) ;


toa s t . show ( ) ;
return t rue ;

. <M EN U>
.

1 0

248

Color , Fot
Style - .
.
. 1 0.6.

Red

Regu l a r

G r e e r1

Bold

Blue

Ita l i c

. 1 0.6.

11


.
, , .
,
.
, (
) .
,
. ,
,

.

1 1 . 1 .
- , Adroid
, , ,
.
:
(active wru running) -

. ,
;
u (paused) - ,

.
.

;
(stopped) -

1 1

250

, ,
.
, ,
,
.
,
:
CJ protected void onC reate ( Bundle s avedins tanceState ) ;
CJ protected void onStart ( ) ;
[J protected void onRes tart ( ) ;
[J protected void onRe sume ( ) ;
[J protected void onPaus e ( ) ;
[J protected void onS top ( ) ;
[J protected void onDest roy ( ) .

- ,
,
.

onC reate ( ) ,
.
onPause ( ) ,
.

. :
protected void onPause ( )
super . onPause ( ) ;


. ,
:
CJ

: (enti1e lifetime) -
onCreate ( ) onDe s t roy ( ) .
. onC reate ( )
onDe s t roy ( ) ,
,
.

25 1

,
onDe s t roy ( ) ;

onCreate

( )

D (visi/e lifetime) -

( ) onStop ( ) .
,
.
, ,
;
ons tart

D (foregrond lifetime) -
onResume ( ) onPause ( ) .
.

active pased,
(
), ,
, .

1 1 . 1 ,
. ,
,
. ,
,
, .


:
D onC reate ( ) - .

-
, . .
- undle,
( );
D onRe s t a rt ( ) - ,

.
onStart ( ) ;
D onS tart ( ) - ,

.
onRe sume ( ) , ,
onstop ( ) , ;
D onResume ( ) - ,

.
onPause ( ) ;

1 1

252


. _____L___-,
"Back" o Restart()

. 1 1 . 1 .

onPause ( ) - ,

. ,
,
n n
. n onRe sume ( ) ,
n n, ons top ( J ,
n ;

253

onStop ( ) - ,

. ,
( ),
.
onRe s t a rt ( ) , ,
, onDe s t roy ( )
;
,

onDe s t roy ( ) - . -

, .
,
finish ( ) ,
.
i s Fini shing ( ) .
,
.

1 1 . 1 . 1 .
n n,
,
.
,
onSave instance State ( ) .
Android , . .
onPause ( ) .
n undle,
, - .
, undle
onCreate ( ) onRes tore i nstance State ( ) ,
n ons tart ( ) ,
.
onPause ( ) , ,
on Save ins t ance State ( ) onRes tore i ns t ance State ( )
.
. , Android onSave i nstance S tate ( ) ,
,
,
( <>).
.

254

1 1

onSave instanceState ( ) ,

. on Pause ( ) .

1 1 . 1 . 2 .
,
.
. < >,
,
, .
.
, .
( )
.
,
Activity,
. ,
.
, ,
.

1 1 . 2 .
(
, ) ,
. -

.
, Intent,
, .
Intent Context . startActi v i ty ( )
Act i vi ty . s t a rtAct i vi tyForRe sul t ( ) ,
- . Intent
Act i vi ty . setResul t ( ) ,
,

startAct ivi tyForResult ( ) .

Android ,
, .

255

Intent - . ,
, , ,
. , Intent
, Adroid, -
,
. , Intent
:
. ,

. - ComponentNarne -
(, "MainAct ivi t y " )
,
( , " com . sarnpl es . application " ) .
. , Intent
. , Adroid
Intent,
.
setComponent ( ) , setClass ( )
setClas sNarne ( )
getComponent ( ) ;
. , . Intent

, :

ACT ION_CALL -

ACT ION_EDIT -

ACT ION_AIN -

ACT ION SYNC -

,
;
_

.
,
, ,
.

. , ,
,. com . sarnples . proj ect . u s_
ACT ION . Intent setAc t i on ( )
getAct ion ( ) ;
u . U RI M I M E .

.
15;
. ,

, .

Intent

256

1 1

.
CATEGORY, :

Intent

CATEGORY_BROWSALE -
, ,
;

Screen, ,

, < >;


Application Launcher
(
).

CATEGORY_ -

CATEGORY_LAUNCHER -

Intent

addCategory ( )

removeCategory ( )

getCategories ( )

Intent;

- , ;

-
Intent;

D . - ,

, .
, ACT ION_T IMEZONE_CANGED t ime - z one,
, ACT I ON_HEADSET_PLUG
s tate, , ,
name . Intent
put
( )
get . ( ) .
undle

putExtras ( ) getExt ras ( ) ;

D . , (,

)
, (,
).
Intent .

Android , Q ,
Intent
( ,
).

257

1 1 . 3 .
:
' - (

, , );
- (

- ). ,
.
,
,
.

. (
. 1 1. 5) . n
Andid
( ,
),
.

1 1 . 4 .

,

,
,

s t a rtActi vi ty ( Intent ) .
rntent, , .
, .
, ,
.
, : .
, s tartActivityForResult ( Intent ,
int ) , .
onAct ivityRe sult ( int , int , I ntent ) ,
.
1 1
pr ivate s t a t i c final int I DM ADD
Intent intent

new Intent ( ) ;

101 ;

258

1 1

intent . setClas s ( th i s , NewContactActivi t y . c l a s s ) ;


1 /
sta rtActivityForResult ( intent , I DM_NEW ) ;

, setResult ( int ) ,
.
,
RESULT_CANCELED, RESULT_
RESULT FIRST USER.
private EditText mName ;
private EditText mPhone ;
I ntent i ntent

new I ntent ( ) ;

1 1

.
intent . putExtra ( ContactLis tAc t i vi ty . N ,
mName . getText ( ) . toString ( ) ) ;

intent . putExtra ( ContactListAc t ivity . PHON E ,
mPhone . getText ( ) . toString ( ) ) ;

setResul t ( RE SULT_OK , intent ) ;
finish ( ) ;

,
Intent, .

Act i vity . onAct i vityRe sult ( ) , ,
:
protected v o i d onActivityResult (
int reques t Code , int resultCode , Intent data )

supe r . onActivityRe sul t ( reques tCode , resultCode , data ) ;


i f ( resul tCode
Bundl e extras

RESULT_OK )
data . getExt ras ( ) ;

switch ( reques tCode )


case I DM ADD :
S t r ing name
S t r ing phone
brea k ;

extras . get S t r ing ( Contac t i tem . NAE ) ,


extras . getSt ring ( Contact i tem . PHONE ) ) ) ;

259


,
RE SULT_CANCELE D.
. Ecl ipse
Create New Proj ect :
D Project name - ContactEdi tor;
D Application name - Contacts Sample;
D Package name -

sampl es . contactedi tor;

D Create Activity - L i s tContactAct ivity.


,
: ,
. . 7. 5 ,
.
:
D

Contac t L i s tAct ivity -

;
D

NewContactActivity -

Edi tContactActivity -


NewContactAc tivity Edi tContactAct ivity,
1 1 . 1 . ,
android : name android : l abe l .

< ?xml ve r s i on= " . 0 " encoding= " ut f- 8 " ?>


<man i fe s t xmlns : android= " http : / / s chemas . android . com/ap k / res /android"
package= " com . sample s . contactedi tor "
android : ve r s i onCode= " l "
android : ve r s i onName= " l . O " >
<appl ication
android : i con= " @ drawa l e / i con "
android : labe l= " @ s t ring/app_name " >
<act ivi t y android : name= " . Li s tContactActivi ty"
android : l abe l= " @ s tring/app_name " >

1 1

260
<intent - f i lter>
<act ion android : narne= " android . intent . action . AI N "

<category android : narne=" android . intent . category . lAUNCER"


< / intent- f i l t e r>
< /activity>
<act ivi ty
android : narne= " . NewContactActivi t y "
android : l abel= " @ s t ing / t i t l e_add " >
< /act ivity>
<activity
android : narne= " . Edi tContactActivi t y "
android : label= " @ s t ring / t i t l e_edi t " >
< /activity>
< / appl ication>
<uses- sdk andro id : minSdkVe r s i on= " "
< /mani fest>

main .xm l , 7 . 1 9 . 7. 5.
.
,
, res/values/strings.xm l,
1 1 .2 . ,
1 6.

< ?xrnl ve r s i on= " . 0 " encoding= " ut f-8 " ? >
<resources>
< s t r ing narne=" app_narne " >Contacts s arnple < / s tring>
< s t r ing narne="btn_crea t e " >Create < / s t r ing>
< s t ring narne= "btn_save " > S ave< / s t r ing>
< s t r ing narne="btn_cance l " >Cance l < / s t ring>
< s t ring narne= " f ield_narne " >Narne : < / s t r ing>
< s t r ing narne= " field_phone " >Phone : < / st ring>
< s t ring narne= " t i t l e_add" >Add new Contact < / s tr ing>
< s t ring narne= " t i t l e_edi t " >Edit Contact < / s t r ing>
< s t r ing narne= " t i t l e de let e " > Delete this Contact ? < / s t ring>
< s t r ing narne="menu_add " >Add< / s t ring>
< s t r ing narne="menu_edit " >Edi t< / str ing>
< s t r ing narne="menu_de lete " > Delete< / s t r ing>
<st ring narne= " toast_not i f y " > Please select Contact ! < / s t ring>
< / res ources>

261

NewContactActivity EditContactActivity
, n
n n
. n ,
n n.
n 1 1 .3 .

< ?xml ve r s i on= " . 0 " encoding= " ut f - 8 " ?>


<Linea rLayout xmlns : android= " http : / / schemas . android . com/ apk / re s / android"
android : layout_he ight= "wrap_content "
android : layout_width= " fi l l_pa rent "
android : orientat i on= "ve r t i ca l " >
<Linea rLayout
android : layout_he ight = " wrap_content "
android : layout_width= " f i l l_pa rent "
android : or i entation= " hori zontal "
android : padding= " l Opx " >
<TextView
android : l ayout_width= "wrap content "
android : l ayout_he i ght= "wrap_content "
.
and roid : text= " @ s t r ing / field_name "
android : paddingRight= " l Opx " / >
<EditText
androi d : layout_he ight = " wrap_conten t "
android : l ayout_width= " fi l l_pa rent "
android : id= " @ +id/edit name " / >
< / Linea rLayout >
<Linea rLayout
android : layout_he ight= "wrap content "
android : layout_width= " fi l l_parent "
android : orientat i on= " ho r i z onta l "
android : padding= " l Opx " >
<TextView
androi d : l ayout_width= "wrap content "
android : l ayout_he i ght= "wrap_conten t "
android : text= " @ s t r ing / f i eld_phone " / >

1 1

262
<EditText
android : l ayout_he ight=" wrap_conten t "
android : l ayout_width= " f i l l_parent "
android : id= " @ + id/edit_phone " / >
< / Linea rLayout >
<LinearLayout
android : la yout_he ight= "wrap_content "
android : layout_width= " fi l l_parent "
android : or ientation= " hori zonta l "
android : padding= " l Opx " >
<Button
androi d : l ayout_he ight= " wrap content "
android : l ayout_width= " f i l l _parent "
android : l ayout_we ight= "
android : id= " @ + id/but ton save " / >
<Button
android : layout_he ight=" wrap_content "
android : layout_width= " f i l l_pa rent "
android : layout_we i ght= " l "
android : text= " @ s t r ing/btn_cance l "
android : id= " @ +id/but ton cancel " / >
< / Linea rLayout >
< / Linea rLayout >

n n , 7 ( 15
"" n ,
n ).
contac t i t em, n
.
Contacti tem n

1 1 .4 .

package com . sample s . contactedi tor ;


import j ava . ut i l . Hashap ;
pu l i c c l a s s Contact i t em extends Hashap<St ring , St ring>
pr ivate static final long seria lVe r s i onUI D
pu l i c s t a t i c final S t r ing N

" name " ;

pu l i c s t a t i c final S t r ing PHONE = "phone " ;

lL;

263


pulic Contacti tem ( St ring n , Str ing phone )
supe r ( ) ;
supe r . put ( NAE , n ) ;
supe r . put ( PHONE, phone ) ;

pulic S t r ing getNae ( )

return supe r . get ( NAE ) ;

pu l i c St ring get Phone ( )

return supe r . get ( PHONE ) ;

pul i c void setNae ( S t r ing n )


supe r . put ( NAE , n ) ;

pul ic void set Phone ( St r ing phone )


supe r . put ( NAE , phone ) ;

ContactListAc t ivity

.
contactListAct ivity n 1 1 . 5 .

package com . saple s . contacteditor ;


import j ava . ut i l . ArrayList ;
import android . app . Al e rtDialog ;
import android . app . ListAct ivi t y ;
import android . content . Dialoginte rface ;
import android . content . Intent ;
import android . os . Bundle ;
import android . view . Menu ;
import android . view . Menuitem;
import android . widget . ListAdapte r ;
import andro id . widget . S impleAdapter ;
import android . widget . Toa st ;

264

1 1

pu 1 i c c 1 a s s L i s tContactActivity extends L i s tActivity


pr ivate static fina1 int I DM ADD

101;

private s t a t i c fina1 int I DM EDIT


private static fina1 int I DM DELETE
private 1ong mid

102 ;
103 ;

-1 ;

Ar rayLi st<Contact i tern> mLi st ;


private Lis tAdapter mAdapte r ;
@ Ove rride
pu 1 i c void onCreate ( Bund1e savedins tance State )
supe r . onCreate ( savedins tanceState ) ;
mL i s t

n e w ArrayList <Contacti tem> ( ) ;

1 1
f i l l Contacts ( ) ;
updateLi st ( ) ;

private void updateLi s t ( )


mAdapter

new S imp1eAdapte r ( thi s , mLi st , R . 1ayout . ma i n ,


new S t ring [ ]
new int [ ]

{ Contact i tem . NAE , Contacti tem . PHONE } ,

{ R . id . name , R . id . phone } ) ;

setListAdapte r (mAdapte r ) ;

@ Ove r ride
pu i c boo 1ean onC reateOptionsMenu ( Menu menu )
menu . add ( Menu . NONE , I DM_ADD , Menu . NONE , R . s t r ing . menu_add )
. s e t i con ( R . drawale . i c_menu_add )
. setA1phabet i cShortcut ( ' a ' ) ;
menu . add ( Menu . NONE , I DM_EDIT , Menu . NONE , R . s t r ing . menu_edi t )
. s e t i con ( R . drawale . i c_menu_edi t )
. setA1phabeti cShortcut ( ' e ' ) ;
menu . add ( Menu . NONE , I DM_DELETE , Menu . NONE , R . s t r ing . menu_de 1ete )
. se t i con ( R . drawale . i c_menu_de 1ete )
. setA1phabet i cSho rtcut ( ' d ' ) ;
return ( supe r . onCreateOptionsMenu (menu ) ) ;

@Ove r ride
pul i c boo1ean onOpt i ons i temS e 1ected ( Menui tem i tem)
mid

thi s . get Se1ecteditemid ( ) ;

265


swi tch ( item . get i t emid ( ) )
case I DM_ADD :

new Intent ( ) ;
Intent intent
intent . setClas s ( this , NewContactActivity . c l a s s ) ;
1 1
sta rtActivi tyForResul t ( intent , I DM_ADD ) ;
break ;
case I DM EDIT :
if (mid >= 0 )
Contactitem mitem

mLi s t . get ( ( int ) mid) ;

Intent intent
new Intent ( ) ;
intent . putExtra ( Contac t i t em . NAE , mi tem . getName ( ) ) ;
intent . putExtra ( Contact i tem . PHONE , mitem . getPhone ( ) ) ;
intent . setClass ( this , Edi tContactActivi t y . c l a s s ) ;
1 1
sta rtActivit yFo rResult ( intent , I DM_E D IT ) ;
else
Toast . makeText (
this , R . st ring . toast_notify, Toast . LENGTH_SHORT )
. show ( ) ;
brea k ;
case I DM DELETE :
if

(mid >= 0 )
AlertDialog . Builde r bu i lder
new AlertDia log . Builde r ( thi s ) ;
Contact item mitem
mLi s t . get ( ( int ) mid) ;
builde r . setMes s age ( R . s t ring . t i t l e_de lete + " \n "
+ mi tem . getName ( ) + " \n " + mitem . getPhone ( ) ) ;
=

builde r . s e t Pos i t iveButton (


"Yes " , new Dialoginte r face . OnCl i c kL i s tene r ( )
pul ic void onClick ( Dialoginterface dialog , int id)
mLi s t . remove ( ( int ) mid ) ;
updateLi s t ( ) ;
}) ;
builde r . s etNegat iveButton (
"No " , new Dia loginter face . OnCl ickLis tene r ( )
pulic void onCl ick ( Dialoginterface dialog , int id)
dialog . cancel ( ) ;
}

266

1 1
bui1de r . setCance1ale ( fa 1 s e ) ;
bu i 1de r . show ( ) ;
e1se
Toast . makeText ( this , R . s t r ing . toast_not i fy ,
Toast . LENGTH SHORT )
. show ( ) ;
updateLi st ( ) ;
break ;
return ( supe r . onOptions i temSe 1ected ( i tem) ) ;

protected void onAct ivityResu1t (


int requestCode , int resu1tCode , Intent dat a )
supe r . onActivityRes u1t ( reque stCode , resu1tCode , data ) ;
i f ( resu 1 tCode
Bund1 e extras

RESULT_OK )
data . getExt ras ( ) ;

switch ( requestCode )
case I DM ADD :
mLi s t . add ( new Conta c t i tem (
ext ras . getS t r ing ( Contact i tem . NAE ) ,
ext ra s . getS t r ing ( Contac t i tem . PHONE ) ) ) ;
bre a k ;
c a s e I DM EDIT :
mLi s t . s et ( ( int ) mid, new Contac t i tem (
extras . getS t r ing ( Contacti tem . NAE ) ,
ext ras . getS t r ing ( Conta c t i tem . PHONE ) ) ) ;
bre a k ;
updateLi st ( ) ;

pul i c void f i 1 1Contacts ( )


mLi s t . add ( new Contacti tem ( " Jacob Ande rson " , " 4 1 2 4 1 2 4 1 1 " ) ) ;
mLi s t . add ( new Contacti tem ( " Emi 1 y Duncan " ,

" 1 61 8 63 1 8 7 " ) ) ;

mLi s t . add ( new Contact i tem ( "Michae1 Ful le r " , " 8 9 6 4 4 3 65 8 " ) ) ;
mLi s t . add ( new Contacti tem ( " Emma Greenman " ,

" 9 64 990543 " ) ) ;

mLi s t . add ( new Contacti tem ( " Joshua Har r i s on " , " 7 5 92 8 5 0 8 6 " ) ) ;
mLi s t . add ( new Contacti tem ( "Madison Johnson " , " 9 5 0 2 8 5 7 7 7 " ) ) ;

267


rnL i s t . add ( new Contact i t ern ( "Matthew Cotrnan " ,
rnL i s t . add ( new Contact i tern ( " Olivia Laws on" ,

" 68 7 6 9 9 9 9 9 " ) ) ;
" 1 61 8 6 3 1 8 7 " ) ) ;

rnL i s t . add ( new Contacti tern ( "Andrew Chaprnan " ,

" 5 4 6 5 9 9 64 5 " ) ) ;

rnList . add ( new Contact i tern ( " Dani e 1 Honeyrnan " , " 8 7 6 5 4 5 6 4 4 " ) ) ;
.
" 907868756 " ) ) ;

rnList . add ( new Contact i tern ( " I sabe l l a Jackson " ,

rnList . add ( new Cont act i tern ( "W i 1 1 i arn Pat terson " , " 6 8 7 6 9 9 6 9 3 " ) ) ;
rnList . add ( new Contact i t ern ( " Joseph Godwin " ,

" 9 654 67575 " ) ) ;

rnList . add ( new Contact i tern ( " Sarnantha Bush" , " 9 0 7 8 6 5 6 4 5 " ) ) ;
rnL i s t . add ( new Contact itern ( " Chr i s t ophe r Gat ernan " ,

" 8 9687 4 55 6 " ) ) ;

Newcont actActivity

. NewContactActivity
1 1 .6 .

package corn . sarnples . contactedi tor ;


irnport android . app . Act ivi t y ;
irnport android . content . Intent ;
irnport android . os . Bund1e ;
irnport android . view . View;
irnport android . widget . Button ;
irnport android . widget . EditText ;
pul ic c1ass NewContactActivity extends Act ivity
pr ivate Edit}ext rnNarne ;
private EditText rnPhone ;
@ Ove r ride
pul i c void onCreate ( Bund1e savedinstance State )
supe r . onCreate ( savedinstanceStat e ) ;
s etContentView ( R . 1ayout . contact_ itern) ;
rnNarne
rnPhone

( EditText ) f indVi ewByld ( R . id . edit narne ) ;


( Edi tText ) findVi ewByid ( R . id . edit _phone ) ;

fina1 Button btnOK

( Button ) findViewByid ( R . id . button_save ) ;

fina1 Button btnCancel

( Button) findViewByid ( R . id . button_cance1 ) ;

btnOK . s etText ( R . s t r ing . btn_create ) ;

268

1 1
btnOK . setOnCl ickLis tener ( new View . OnC l i ckLi stene r { )
@ Ove rride
pu l i c vo id onCl i c k ( View v )
Intent intent
new Intent { ) ;
i n tent . putExtra ( Contactitern . NAE ,
rnNarne . getText ( ) . to S t r ing { ) ) ;
intent . putExt ra ( Contact i tern . PHONE ,
rnPhone . getText ( ) . toString ( ) ) ;
setRe sult ( RE SULT_OK , intent ) ;
finish ( ) ;

btnCance l . s etOnCl ickListene r ( new View . OnC l i c kL i s tene r ( )


@ Override
pu l i c vo id onC l i c k (View v )

setResult ( RESULT_CANCELE D ) ;
finish ( ) ;

EditContactAc t ivity

. ,
NewContactActivity,
. EditContactAct ivity
1 1 .7.

package corn . sarnples . contactedi tor ;


irnport android . app . Activity ;
irnport android . content . Intent ;
irnport android . os . Bundle ;
irnport andro id . view . View ;
irnport andro id . widget . Button ;
irnport android . widget . EditText ;
pul i c class EditContactActivity extends Act ivity {
private EditText rnNarne ;
p r ivate Edi tText rnPhone ;

269


@ Ove rride
pu l i c void onCreate ( Bundle savedins tance State )
supe r . onCreate ( savedinstanceState ) ;
set ContentView ( R . layout . contact_i tem) ;
mName
mPhone

( Edi tText ) findVi ewByid ( R . id . edi t_name ) ;


( Edi tText ) findVi ewByid ( R . id . edit_phone ) ;

final Button btnOK

( Button ) findViewByid ( R . id . button_save ) ;

final Button btnCance l


( Button ) findViewByid ( R . id . button_cancel ) ;
btnOK . s etText ( R . s t r ing . btn_save ) ;
Bundle ext ras

get i ntent ( ) . getExt ras ( ) ;

mName . s etText ( extras . get St ring ( Contact item . NAE ) ) ;


mPhone . s etText ( ext ras . get S t r ing ( Conta c t i tem . PHONE ) ) ;
btnOK . s etOnCl i c kListene r ( new View . OnC l i ckListene r ( )
@ Override
pu l i c void onCl i c k (View v )
Intent intent
new Intent ( ) ;
intent . putExt ra ( Contact i tem . NAE ,
mName . getText ( ) . toString ( ) ) ;
intent . putExt ra ( Contact i tem . PHONE ,
mPhone . getText ( ) . to S t r ing { ) ) ;
setResult ( RE SULT_OK , intent ) ;
finish ( ) ;

btnCancel . setOnCl i c kL i s tene r ( new View . OnC l i ckLis tene r ( )


@ Ove rride
pu l i c vo id onC l i c k ( View v)

setResult ( RESULT_CANCELE D ) ;
finish ( ) ;


(. 1 1 .2).

, ( )
(. 1 1 .3 ) .

270

. 1 1 . 2.

. 1 1 . 3 .

11

271


RESULT_CANCELE D)
,
.

( RE SULT_o

1 1 . 5 .

, .
.
,
. ,
.

rntent : , , .
, .
< intent
f i l ter>. , ,
:
<activity
android : name= " . ContactLi stActivity"
android : l abe l= " @ st ring/ app_name " >
< intent - f i lter>
<act i on andro id : name=" andro id . intent . action . AIN "
<category android : name=" android . i ntent . category . LAUNCHER"
< / intent - f i lter>
< / act ivity>

<act ion> ,
. <catego ry>
Application Launcher,

, .

0
- I ntent F i l t e r . , . .
A droid ,
,

.

<intent- f i l t e r > ,

272

1 1

, ,
Intent.
. , ,
. ,
- , .
, . . , ,
,
.
, .
contactListAct ivity

Contacts,
ContactLi stAct ivity, 1 1 . 8 .

<activity
android : name= " . ContactLis tActivity"
android : labe l= " @ st ring / app_name " >
< intent - f i lter>
<act i on andro id : name=" android . intent . act i on . AIN "
<category android : name= " android . intent . category . LAUNCHER"
< / intent - f i l te r>
< intent - f i l te r>
<act i on andro id : name= " c o . samples . contact . VIEW_CONTACT S "
<category android : name= " android . intent . category . DEFAULT "
< / intent- f i lter>
< / activi ty>

act ion android : name=" co . s amples . contact . VIEW_CONTACT S "


. ContactLis tAct ivity
Intent
" . s amples . contact . VIEW_CONTACTS " ,
.

contactLi stAct ivity

Proj ect name - Contact Launche r;


Application name - Contact Launche r S ample;
Package name - . samples . cont act launcher;
Create Activity - Contact Launche rAct ivity.

273

.
1 1 .9 .

< ? xml ve r s i on= " l . O " encoding= " ut f- 8 " ?>


<Linea rLayout xmlns : android= " http : / / s chernas . android . com/ apk / re s / android"
android : orientation= "vert i ca l "
android : layout_width= " fi l l_pa rent "
andro id : layout_he i ght= " fi l l_parent "
android : gravi ty= " cent e r " >
<But ton
android : id= " @ + id/btn launch "
android : layout_width= "wrap_content "
android : layout _he ight= "wrap_content "
android : text= " Launch Contacts Appl icat ion " / >
< / L inearLayout>

I II 1 1 . 1 .

pac kage com . samples . contactlaunche r ;


import android . app . Activi t y ;
import andro id . content . Intent ;
import android . os . Bundle ;
import android . view . View ;
import android . widget . Button ;
pu l i c class ContactLaunche rActivity extend Act ivity
/ / ,
pr ivate final stat ic S t r ing ACT I ON_VIEW_CONTACTS
" c om . samples . contact . VIEW_CONTACTS " ;
@ Ove rride
pul ic void onCreate ( Bundle savedi nstanceStat e )
supe r . onCreate ( savedi ns tance Stat e ) ;
set ContentView ( R . layout . main ) ;
final Button btnLaunch

( Button ) f indViewByid ( R . id . btn_l aunch ) ;

2 74

1 1

btnLaunch . s etOnC l i c kL i s t e ne r ( new V i ew . OnC l i c kL i s tene r ( )


@ Ove r r ide
pu l i c void onC l i c k ( V iew v )

Cont a c t s

s t a rtAct ivi ty ( new Intent (ACTION VIEW CONTACT S ) ) ;


_
_

.
Cont a c tEdi tor (. 1 1 .4 )
.

. 1 1 .4 .

12

Adroid .
, ,
.
, -
.
.

.

1 2 . 1 .
(. 1 1)
, ,
. :
vo id onCreate ( ) ;
vbid onStart ( Intent intent ) ;
void onDe st roy ( )

,
.
:
Jf :


onC reate ( ) onDe s t roy ( )
, oncreate ( )
onDe s t roy ( ) ;

s t a r t S e rvice ( ) .

:JICUI :J1
onS tart ( )
rntent,
-

276

12


Context . startService ( ) ,
Cont ext . stopServi ce ( )
, S e rvice . stopSe l f ( )
Service . s topSel fResult ( ) .


.
Context . bindservice ( )
Context . un indS e rvice ( ) . ,
indService ( ) .
onCreate ( )
,

Context . startService ( )

Context . indService ( ) . onstart ( )


, startService ( ) .
onDe s t roy ( )

. 1 2 . 1 . ,
startService ( ) ,
bindS e rvice ( ) , , , ,

onReind()

. 1 2. 1 .

277

,
, . . onind ( )
onUn ind ( )

,
:
CJ IBinde r onBind ( Intent intent ) ;
CJ boolean onUnind ( Intent intent ) ;
CJ void onRebind ( Intent intent ) .

onind ( ) Intent,
indService ( ) , onUnind ( ) Intent, unindService ( ) .
, onind ( ) ,
, .
onReind ( ) onUnind ( ) ,
.

1 2 . 2 .
, ,
S e rvice.
onBind ( ) oncreate ( ) , :
import android . app . S e rvice ;
import andro id . content . I ntent ;
import android . os . I Binde r ;
pu l i c class MyService extends S e rv i ce
@ Ove r ride
pu l i c IBinder onBind ( I ntent intent )
1 1

@ Ove r ride
pul i c void onCreate ( )
1 1


onStart ( ) . , -

278

1 2

startService ( ) , ,
:
@ Ove rr ide
pu l i c void onStart ( Intent intent , int s t a r t i d )
1 1 .

,
. < s e rvice>
<application> . < s e rvice>,
,
,
< requ i res -penni s s ion> . ,
MyService :
< ? xrnl ve rs ion= " . 0 " encoding= " ut f- 8 " ? >
<mani fe s t xrnlns : android= "http : / / schemas . androi d . com/apk/ res / android "
<appl ication
android : icon= " @ drawa l e / i con "
android : labe l= " @ s t ring/app_name " >
< s e rvice
android : enaled= " t rue "
android : name= " . MyService " >
< / s e rvi ce>
< / app l icat i on>
< /man i fe s t >

,
s ta r t S e rvice ( ) :
D ;
D .

MyService

startS ervice ( new Intent ( th i s , MyService . c l as s ) ) ;

, .
:
s tartS ervice ( new Intent (MyService . SERVICE_ACT I ON ) ) ;

279

,
, MyS e rvice, :

SERVICE_ACT I ON,

pr ivate static S t r ing SERVI CE_ACT ION

" . s amples . edia . PLAYER " ;

,
SERV I CE_ACT ION.
, ,
Securi tyException.
, stopS e rvice ( )
, :
s t opService ( new Intent ( thi s , s e rvice . getClass ( ) ) ) ;

startService ( ) , ,
onstart ( ) .
startService ( ) , ,
s t opService ( )
, startService ( ) .
-.
,
. .
Create New Project
:
Project name - S e rviceLaunche r;
Application name - S e rvice Launche r Sample;
Package name - . samples . s e rvicelaunch;
Create Activity - LaunchAc t ivi ty.

PlayService.
sample.mp res/raw/ (
).
1 2. 1 .

pac kage co . samples . s e rvice launch ;


iport android . app . Service ;
iport andro id . content . Intent ;
iport android . edia . Medi aPlaye r ;
iport andro id . os . I Binde r ;
iport android . widget . Toas t ;

280

12

pulic class PlayService extends Service {


MediaPlayer mPlaye r ;
@ OVe rride
pulic IBinde r onBind ( Intent intent )

return nul l ;

@OVe rride
pu l i c void onCreate ( )

Toas t . makeText ( thi s ,


Toas t . LENGTH_SHORT ) . show ( ) ;

" Se rvice Created" ,

mPlaye r = MediaPlayer . create ( th i s , R . raw . sampl e ) ;


mPlaye r . setLooping ( fa l se ) ;

@OVe rride
pu l i c void onStart ( Intent intent ,
Toas t . ma keText ( this ,
Toast . LENGTH_SHORT ) . show ( ) ;

int startid)

" Se rvice Started" ,

mPlaye r . s tart ( ) ;

@OVe rride
pu l i c void onDe s t roy ( )
Toast . ma keText ( thi s ,
Toast . LENGTH_SHORT ) . show ( ) ;

{
" Se rvice Stopped" ,

mPlayer . s top ( ) ;

( 1 2.2).

< ?xml ve rsion= " l . O " encoding= " utf-8 " ?>
<manifest xmlns : andro id= " ht tp : / / s chemas . android . com/apk/res / android"
package= " c om . samples . s e rvi ce l aunch "
android : ve r s i onCode= " l "
android : ve r s ionName= " l . O " >
<appl icat ion
android : icon= " @ drawale/ icon "
android : label= " @ s t ring /app_name " >

281

<activity
android : name= " . LaunchActivity"
android : label= " @ st ring / app_name " >
<intent-fi lter>
<action androi d : name= " android . intent . action . AI N " / >

<category android : name="android . intent . category . LAUNCER" / >


< / intent - f i lter>
< / activity>
<service
android : enal ed= " t rue "
android : name= " . PlayServi ce " >
< / s e rvice>
< / appl ication>
<uses-sdk android : minSdkVe r s i on= " "
< /mani fest>

, Start Player
Stop Player ( 1 2.3).

< ? xml ve r s i on= " l . O " encoding= "ut f- 8 " ?>


<Linea rLayout xmlns : android="http : / / schemas . android . com/ apk/res /android"
andro id : orientati on="ve r t i ca l "
android : l ayout_width= " fi l l_pa rent"
android : layout_he ight= " fi l l_parent "
android : gravity= " cente r " >
<Button
android : layout_he ight= "wrap content "
android : id= " @ + id/btn_s tart "
android : text= " Start Playe r "
android : layout_width= " fi l l_pa rent " / >
<Button
android : id= " @ + id/btn_s top"
android : l ayout_he i ght=" wrap_content "
android : text=" Stop Playe r "
android : layout_width= " fi l l_pa rent " / >
< / LinearLayout>


startService ( ) stopService ( ) .
1 2 .4 .

282

1 2

package com . samples . s e rvice launch ;


import android . app . Act ivi t y ;
import android . content . Intent ;
import android . os . Bundl e ;
import android . view . View;
import android . widget . Button ;
pu l i c c l a s s LaunchAct ivi ty extends Act ivi t y
@ Ove rride
pul i c void onCreate ( Bundle s avedinstance State )
supe r . onCreate ( savedinstanceState ) ;
setContentView ( R . layout . main ) ;
final Button btnStart
f inal Button btnStop

( Button ) findViewByi d ( R . id . btn_s tart ) ;


( Button ) f indViewByi d ( R . id . btn_s t op ) ;

1 1
btnStart . s etOnClickLis tener ( new View . OnCl i c kL i s tene r ( )
@Ove r r i de
pu l i c vo id onCl i c k (View v )
1 1
startService (
new I ntent ( LaunchActivi ty . thi s , PlayService . class ) ) ;

1 1
btnS top . s etOnC l i ckLis tene r ( new View . OnCl i c kLis tener ( )
@ Ove rride
pu l i c void onCl i c k (View v )
stopSe rvice (
new Intent ( LaunchAc t ivity . th i s , Pl ayService . clas s ) ) ;

. 1 2 .2.
,

283

:
, .

. 1 2. 2 .

13



, -
.
.
B roadcastRecei ver
,
s endroadcast ( ) .
BroadcastRecei ver
Context . regi s t e rReceive r ( ) ,
< rece ive r> .
,
:
(Normal broadcasts) -

Context . s endroadcast l-/


.
, . , ,
;
(Ordered broadcasts),

Context . s endOrde redroadca st ( ) .


.
,
,
.
androi d : priority ; ,
, .
I ntent
, -

286

1 3

, , ,
Context . s t a r tAct i vi ty ( ) .
Broadca s tReceiver
, sta rtAc t i vi t y ( ) . ,

Broadcas tReceiver,
. :
,
,
.
, ,
, .
Broadcas tRece iver (
< recei ver> )
.

1 3 . 1 .


:
void onRece ive ( Context curContext , Intent broadcas tMs g )

,
Android onReceiv e ( )
Intent, .
. ,
roadca stReceiver, . .
onRece i ve ( ) ,
Android, ,
.
onReceive ( ) ,
, roadcas tRece iver .

. , ,
, ,
, .
,
. onRecei ve ( )

287

, , ,
, Android (
),
.
,
roadcas tRece ive r. n
Not i ficationanager.
Context . s tartService ( ) ,
.

, onReceiv e ( )
Broadcas tReceiver
,
.

1 3 . 2 .
Adroid
, , ,
, , ,
SMS .
,
, .
,
I ntent.
,
:
,
. RECEIVE_oo_coPLETED;

ACT ION_oo_cOMPLETED ACT ION_R_uN -

<Camera> ;
0 ACT ION_DATE_CANGE D ACT ION_I_CANGED -

;
0 ACT ION_SCREEN_OFF ACT ION_SCREEN_ON - ,

;
ACT ION_T IEZONE_CANGED -

288

1 3

1 3 . 3 .

,
.

11 12
.

sendroadcast ( ) .
, ,
,
.


.
; ,
,
, ,
.

, (
)
.

1 3 . 3 . 1 .
.
, ,
sendroadcast ( ) , .
action, data category (, )
,
"" .
,

, ,
.
, ,
Java. ,
( . ) :
pr ivate static S t r ing ACT ION

" corn . sarnples . rnedia . PLAYER" ;

,
ACT I ON -

289

, Intent,
sendroadca s t ( ) ,
Intent :
pri vate s ta t i c final St ring = " type " ;
private static final int I D_ACTION_PLAY = ;
Intent intent = new Intent ( ACT ION ) ;
intent . putExtra ( TYPE ,

I D_ACTI ON_PLAY ) ;

s endroadca s t ( intent ) ;

1 3. 3 . 2 .

,
.
, ,
, .
<applicat ion> <receiver>,
.
<rece ive r> <intent - f i lter>,
. ,

(. ) :
<appl ication
< receiver android : name= " . Pl aye rRece ive r " >
<intent - f i lter>
<act i on android : name= " com . samples . media . PLAYER" />
< / intent- filter>
< / rece ive r>
< / appl i cat i on>


, ,
Broadca s tRe cei ver, onRecei ve ( )
, :
pu l i c clas s PlayerReceive r extends BroadcastRece iver {
priva te static final St ring = " t ype " ;
pr ivate static final int ID ACTION PLAY = 0 ;
private static final int I D ACTION STOP = 1 ;

290

1 3
@ Ove r r ide
pu l i c void onRece ive ( Context context , Intent intent )
int type

intent . ge t i ntExtra ( TYPE , I D_ACTION_STOP ) ;

switch ( type )
case I D ACT ION PLAY :
/ 1
context . s tart Service ( new Intent ( context , PlayService . c las s ) ) ;
brea k ;

onRece ive ( )
.
n n
.

1 3 . 3 . 3 . -

n
n ,
, ,
LaunchActivity, ,
. Ecl ipse
n:
Proj ect name - BroadcastRece i ve r;
Package name - . sarnples . broadcast receive r .


Playe rReceiver PlayService,
1 3 . 1

< ? xrnl ve r s i on= " . 0 " encoding= " ut f- 8 " ?>


<rnani fest xrnlns : androi d= " http : / / s chernas . android . com/ap k / r e s / andro id"
package= " corn . sarnples . broadcast receive r "
andro id : vers ionCode= " l "
android : ve rsionNarne= " l . O " >
<app l i cat i on
android : i con= " @drawa l e / i con"
android : labe l= " @ s t ring/app_narne " >

29 1


<service
android : enaled= " t rue "
androi d : name= " . PlayS e rvice " >
< / s e rvice>
< receive r android : name= " . Pl ayerReceive r " >
<intent - f i lter>
<act i on android : name=" corn . s amples . rnedia . PLAYER"
< / intent- f i l t e r >
< / receiver>
< / appl icat i on>
<us e s - s dk android : rninSdkVers i on= " "
< /rnan i fe s t >

,
, 1 3 .2 .

roadcastReceiver,

package corn . sample s . broadca st receive r ;


irnport android . content . Broadcas tRece ive r ;
irnport android . content . Context ;
irnport android . content . Intent ;
irnport android . widget . Toas t ;
pu l i c c l a s s PlayerRece ive r extends BroadcastRece iver {
pr ivate s t a t i c final S t r ing

" type " ;

pr ivate static final int I D ACT ION PLAY

private static final int I D ACT ION STOP

1;

@ Ove rride
pu l i c void onRece ive ( Context context , Intent intent )
int type

intent . ge t i ntExtra ( TYPE , I D_ACT I ON_STOP ) ;

swi t ch ( type )

case I D ACT ION PLAY :


Toa s t . rnakeText ( contex t ,
" Received act ion : play" , Toas t . LENGTH_LONG ) . show ( ) ;

context . s t artService ( new I ntent ( context , PlaySe rvi ce . c las s ) ) ;
brea k ;

1 3

292
c a s e I D ACT ION STOP :
Toas t . rnakeText ( context ,

" Rece ived action : stop " , Toas t . LENGTH_LONG ) . show ( ) ;



context . s topService ( new Intent ( context , PlayService . clas s ) ) ;
bre a k ;


1 2 . 1 .

Playservice,

12,

- .
,
.

1 3 . 3 .4. n -


- ,
. Ecl ipse
:
D Project name - Broadcast Sende r;
D Application name - Mus i c
D Package name -

Launche r Sample;

. samples . broadcasts ende r;

D Create Activity - LaunchAct ivity.

1 2 .3 . LaunchActivity
, ,
.
LaunchActivity 1 3 .3 .

pac kage com . sample s . broadcastsende r ;


import android . app . Activi t y ;
import andro id . content . Intent ;
import android . os . Bundle ;
import andro id . view . View;
import android . widget . But ton ;

293

pu l i c c l a s s LaunchActivity extends Act ivity


private static String ACION

" . sarnples . rnedia . PLAYER" ;

private static final St ring

" type" ;

private static final int I D ACT ION PLAY


private static final int ID ACION STOP

1;

@ Ove r r ide
pulic void onCreate ( Bundle s avedinstanceStat e )
supe r . onCreate ( savedinstance State ) ;
setContentView ( R . layout . rnain ) ;
( Button )

final Button btnStart


final Button btnStop

( Button )

findViewByid ( R . i d . btn_s tart ) ;


findViewByid ( R . id . btn_s top ) ;

btnS tart . s etOnClickListene r ( new View . OnCl ickListene r ( )


@Ove rride
pulic vo id onCl i c k ( View v)

1 1
Intent intent = new Intent (ACT ION ) ;
intent . putExt ra ( TYPE ,

I D_ACT ION_PLAY ) ;

s endroadcast ( intent ) ;

btnS top . setOnClickListene r ( new View . OnClickLis tene r ( )


@Ove rride
pulic void onClick ( View v)

1 1
Intent intent = new Intent ( ACTION ) ;
intent . putExt ra ( TYPE ,

I D_ACTION_STOP) ;

sendroadcast ( intent ) ;


, 12 ( . . 1 2.2),

.

14



Adroid n
:

nn (Prefereces);

nn -
n n.
.

1 4 . 1 .
Adroid n
(n, SD-).
n .
n - Adroid n
Jv-n. Adroid n n ,
n n j ava. io (. 1 4 . 1 ). n java.io
n n n
.

,
( ) n n .
Jv- Fileinput Stream. n,
:

Context . openFi l e i nput

Input Stream inSt ream

openFi l e i nput ( fi l e . txt ) ;

Input StreamReade r s r = new Input St reamReader ( inStream) ;

296

14

11
Buf fe redReade r reade r

new Buffe redReader ( s r ) ;

Str ing s t r ;
Str ingBuffer buffer

new S t r i ngBuffer ( ) ;

1 1
whi l e ( ( s t r

reade r . readLine ( ) )

nul l )

buffe r . append ( s t r + " \n " ) ;

inStrearn . close ( ) ;

O bj e c t

l n p u t S tre a m

O u tp u tS tre a m

Reader

1
1
1

F i le l n p u tS tre a m

F il e O u tp u tS tre a m

l n p u tS tr e a m R e a d e r

uffe r e d R e a d e r
S tri n g R e a d e r
W r ite r

O u tp u tS tre a m W rite r
B u ffe re d W rite r
S tr i n g W rite r

1
1
1
1
1

. 1 4. 1 . - Android

, context .
.
FileOutputSt rearn.
,
. file.txt :
openFi leOutput ( ) ,

S t r ing data ;
Output St rearn out St rearn
OutputSt rearnWr iter sw
sw . wr ite ( data ) ;
sw . close ( ) ;

openFileOutput ( fi l e . txt , 0 ) ;
new OutputStrearnWr iter ( outStrearn) ;

29 7

, n n
n n, n
n res/raw/, Resource s . openRawResource ( ) .
Input st rearn, n
. n ,
close ( ) .
0
openFi l e i nput ( ) openFileOutput ( )
( , pathlfileslfi l e . txt) , .

n n, n
, n Editext
n .
Ecl i pse n, n n New Android Proj ect:
D Proj ect name - Cont actEditor;
D Application name - Read-Write File Sample;

D Package name - com . sampl e s . f i l e s rw;


D Create Activity - EditorAct ivity.

L- main.xml,
Editext, n '? 1 4. 1 .

< ? xml ve r s i on= " l . O " encoding= " ut f - 8 " ?>


<LinearLayout xmlns : android= " http : / / schema s . android . com/ apk / r e s / andro id"
android : layout_width= " f i l l_pa rent "
android : layout_he i ght= " fi l l_parent "
android : orienta t i on= " ve rt i ca l " >
<EditText
android : id= " @ + id/edi t "
android : la yout_width= " fi l l_parent "
android : layout_he ight= " f i l l_parent "
android : s ingleLine= " fa l s e " / >
< / LinearLayout>

n EditorAct ivity n
n - Open, Save Exit. openFi l e ( )
saveFi le ( ) n , n
. EditorAct ivi t y n 1 4 .2.

298

1 4

package com . sample s . fi l e s rw ;


import j ava . io . Buffe redReader ;
import j ava . io . InputSt ream ;
import j ava . io . InputSt reamReader ;
import j ava . io . Output St reamWrite r ;
import android . app . Activi t y ;
import android . os . Bundle ;
import android . view . Menu ;
import android . view . Menui tem;
import android . widget . EditText ;
import android . widget . Toas t ;
pulic c l a s s EditorActivity extends Activity
pu i c s t a t i c final int I DM OPEN

101;

pul i c s tat i c final int I DM SAVE

102 ;

pul i c stat i c final int I DM EXIT

103 ;

pr ivate final s t a t i c S t ring FI LENAE

" f i le . txt " ;

pr ivate EditText mEdit ;


@ Ove r ride
pu l i c void onCreate ( Bundle i c i c le )
supe r . onCreate ( i c i c 1e ) ;
setContentView ( R . layout . main ) ;
mEdit

( EditText ) findViewByid ( R . id . edit ) ;

@ Ove rride
pu l i c boolean onC reateOpt ionsMenu ( Menu menu )

menu . add (Menu . NONE , I DM_OPEN , Menu . NONE , " Open " )
. se t i con ( R . drawale . i c_menu_open)
. s etAlphabet icShortcut ( ' o ' ) ;
menu . add ( Menu . NONE , I DM_SAVE , Menu . NONE , " Save " )
. se t i con ( R . drawale . i c_menu_save )
. setAlphabet i c Shortcut ( ' s ' ) ;
menu . add (Menu . NONE , I DM_EXI T , Menu . NONE , "Exit " )
. s e t i con ( R . drawale . i c_menu_ex i t )
. setAlphabeticShortcut ( ' x ' ) ;


return ( supe r . onCreateOpti onsMenu (menu ) ) ;

@ Ove rride
pu l i c boolean onOpt i ons i temSelected (Menu i tem item)
swi tch ( i tem . get itemi d ( ) )
case I DM OPEN :
openFi le ( FI LENAE ) ;
bre a k ;
c a s e I DM SAVE :
saveFi l e ( FI LENAE ) ;
bre a k ;
c a s e I DM EXIT :
finish ( ) ;
brea k ;
defaul t :
return fa l s e ;
return t rue ;

private void openFi l e ( String f i l eName )


try {
InputSt ream inSt ream
i f ( inSt ream

openFi l e i nput ( FI LENAE ) ;

nul l )

Input S t reamReade r s r
new Input StreamReade r ( inSt ream ) ;
Buffe redReade r reade r

new Bu fferedReade r ( s r ) ;

St r ing s t r ;
S t r ingBuffer buffer
whi le ( ( s t r

new StringBu f fe r ( ) ;

reade r . readLine ( ) )

nul l )

buf fe r . append ( s t r + " \n " ) ;

inS t ream . close ( ) ;


mEdi t . setText ( buffe r . toString ( ) ) ;

catch ( Throwale t )
Toa s t . makeText ( getApp l i cationContext ( ) ,
" Except ion : " + t . toString ( ) , Toa s t . LENGTH_LONG )

299

14

300
. show ( ) ;

pr ivate vo i d s ave Fi l e ( S t r ing Fi l eName )


t ry
Output St r eam out S t ream
Output S t reamW r i t e r sw

openFi leOutput ( FI LENAE ,

0) ;

new Output S tr e amW r i t e r ( out S t ream) ;

sw . w r i t e (mEdi t . getText ( ) . t o S t r i ng ( ) ) ;
sw . c l o s e ( ) ;

catch

( Throwa le t )

Toa s t . makeText ( ge tApp l i c a t i onCont ext ( ) ,


" Except ion :

t . toS t ring ( ) ,

Toast . LENGTH_LONG )

. show ( ) ;

, ,
. 1 4.2.

1 234567890qwerty

. 1 4.2.

n ,
. -

30 1

, ,
, .

1 4. 2 .
-
- .
, ,
, ,
.
( Application
Launcher - Settings).
. 1 4 .3 .

. 1 4. 3 .

Adroid Prefereces Framework,



. Prefereces Framework
. n
. 1 4 .4.
- ,
. L-.
X M L < P r e f e rence S c reen>,

< Prefe rence S c reen>. < P r e f e renceCatego ry> -

302

14


.
:
CJ CheckBox P re ference;
CJ Edi tText Prefe rence;
CJ L i s t P refe rence ;
CJ Ringtone Preference .
O bj e c t

------,

P re fe re n c e

.-----------,
P re fe re n c e G ro u p

1
D i a l o g refe re n c e

1
C h e c k B o x P re f e r e n c e

R i n g to n e P re fe re n c e

P re fe re n c e C a te g o ry

refe re n c e S c re e n

d it e x t P refe r e n

L i s t P refe re n c e

. 1 4.4.


.

,
.
,
Act i vi ty . get Prefe rences ( ) .
( -,
).

1 4. 2. 1 .
Adroid
-. ,
S t ring ( boo lean,
int . .).

303

,
.
.

:
( ) - ,
;

D get Pre fe rences

( ) - ,
;

D getSharedPrefe rences

D getDefaul tSharedPre fe rences

Android.

( ) - Prefe rencesManage r,
,

, .
get Sha redPre ferences ( )
- getPrefe rence s ( ) . getDe faul t Sha redPrefe rences ( )
Context (, ).
Sha redPreference s,
:
D getBoolean ( S t r i ng key , boolean de fVa lue ) ;
D getFloat ( St r ing key , float de fVa lue ) ;
D getint ( St r ing key, int de fVa lue ) ;
D getLong ( S t ring key , l ong de fValue ) ;
D getSt r ing ( S t ring ke y, St ring de fVa lue ) .

get . ( ) - ,
.
, boo lean:
Sha redPre ferences prefs
Pre fe renceManage r . getDefault Sha redPrefe rences ( th i s ) ;
boolean val

prefs . getBoolean ( getSt ring ( R . s t r ing . pre f_i tem) , fals e ) )

,
- ,
, .

1 4. 2 . 2 . CheckBoxPreference
ln- Sha redPrefe rence s .
.

1 4

304

Create New
Project :
D

Project name - Preference s ;

Application name - Prefe rence s

Package name - com . samples . preference s;

Create Activity - LaunchAct ivity.

Sample;

main.xml ,
( . 1 4. 1 ).
.
,
,
res/values/strings.xm l . OpenMode.

, .
strigs.xml ,
, 1 4 . 3 .

< ?xml ve r s i on= " . 0 " encodi ng= "utf-8 " ? >
< re s ource s >
< s t r i ng name= " app_name " > Preferences Sampl e < / s t ring>
< s t ring name= "pr_openmode " >Openode < / s t ring>
< s t ring name="pr_col o r " >Color< / s t ring>
< s t ring name="pr_color_lack" >ColorBlack< / s t r ing>
< s t r ing name="pr_color_red " >ColorRed< / s t ring>
< s t r ing name="pr_color_green " >ColorGreen< / s t ring>
< s t ring name="pr_color_lue " >Col orB l ue < / s t ring>
< s t r ing name= "pr_s i z e " > S i z e < / s t ring>
< s t ring name= "pr_s t yl e " > S t yle< / s t ring>
< s tring name="pr_style_regul a r " >StyleRegular< / s t ring>
<s tring name="pr_style_bold" > StyleBold< / s t ring>
< s t ring name="pr_style_i t a l i c " > Style i t a l i c < / s t ring>
< s t ring name="pr_tone " >Tone< / s t r ing>
< / resources >

,
, ,
. preferences.xml 1 4 .4 .

305

<Prefe rence Screen


xmlns : android= " http : / / s chernas . android . com/ apk / r e s / android" >
<CheckoxPre fe rence
android : key= " @ st ring /pr_openmode "
android : ti t le="Open f i l e "
android : surnrna ry= "To open f i l e at start appl i cat ion " / >
< / P re ferenceScreen>

, L-,
.
onC reate ( )
addPrefe rences FromResource ( ) XML
pecypc ( - preferences.xml),
. PreferencesAct ivity
1 4. 5 .

package com . sample s . prefe rence s ;


import andro id . os . Bundle ;
import andro id . prefe rence . Pre ferenceActivi t y ;
pu l i c c l a s s Pre fe rencesAc t ivity extends Prefe renceAct ivi ty
@ Ove rride
pu l i c void onCreate ( Bundle savedinstance State )
supe r . onCreate ( savedins tance State ) ;

1 1
addPrefe rences FromRe source ( R . xml . pre ferences ) ;


( 1 4 .6).

PreferencesActivity

<?xml ve rs ion= " l . O " encoding= " ut f- 8 " ? >


<rnani fest xmlns : andro id= " ht tp : / / s chernas . android . com/apk/ res /android"
package=" com . s amples . preferences " >
<app l i cat ion andro id : labe l= " @ st ring / app_name " >

306

14
<ac t ivi t y
android : name= " . EditorActivity"
android : l abe l= " @ s t ring/ app_name " >
< intent - f i lter>
<action android : name= " android . intent . action . AIN "
<category android : name= " android . intent . category . IAUNCER"
< / i ntent- filter>
< /a c t ivi ty>
<activity
android : name= " . Pre ferencesEdit "
android : l abe l= " @ s t ring/ app_name " >
< /act ivity>
< / appl ication>

< /mani fe s t >

EditorActivity n
n ( . 1 4.2). n
Settings, nn.
onOptions i temSelected ( ) switch
case nn:
c a s e I DM PRE F :
I ntent intent

new Intent ( ) ;

intent . setCla s s ( this , Pre ferencesActivity . c las s ) ;


sta rtAc t ivity ( intent ) ;
brea k ;

n n onResne ( ) .
Android n n,

. n onRe sne ( )
:
Sha redPre fe rence s prefs
P re fe renceManager . getDe faul t Sha redPre ferences ( thi s ) ;
1 1 CheckoxPre fe rence
if (prefs . getBoolean ( ge t S t r ing ( R . st r ing . pr_openmode ) , fa l se ) )
openFi le ( FI LENAE ) ;

getoolean ( ) ( false )
n, n
.

1 4 .7.

EditorActivity

package corn . sample s . prefe rence s ;


irnport j ava . io . Buf feredReade r ;
irnport j ava . io . Inpu t S t ream;
irnport j ava . io . Inpu t S t reamReade r ;
irnport j ava . io . Output St reamWrite r ;
irnport android . app . Ac t ivi t y ;
irnport andro id . content . Intent ;
irnport android . content . SharedPre fe rence s ;
irnport andro id . graphi c s . Color ;
irnport andro id . g raphi c s . Type face ;
irnport android . os . Bundle ;
irnport android . pre fe rence . PreferenceManage r ;
irnport android . text . rnethod . NumerKeyLis tene r ;
irnport android . view . Menu ;
irnport andro id . view . Menuitern;
irnport andro id . widget . EditText ;
irnport andro id . widget . Toa st ;
pu l i c c l a s s EditorAc t ivity extends Act ivi t y
s t a t i c final int I DM OPEN

101;

s t a t i c final int I DM SAVE

102 ;

s t a t i c final int I DM PREF

103 ;

static final int I DM EXIT

104 ;

private final s t a t i c St ring FI LENAE

" fi 1 e . txt " ;

private EditText rnEdi t ;


@ Ove r ride
pu 1 i c void onCreate ( Bund1e i c i c 1 e )
supe r . onCreate ( ic i c 1e ) ;
setContentView ( R . 1ayout . rnain ) ;
rnEdi t

( EditText ) findViewByid ( R . id . edit ) ;

@ Ove rride
pu l i c void onRe surne ( )
supe r . onRe surne ( ) ;

307

14

308
SharedPrefe rence s prefs
Prefe renceManager . getDe faultSha redPre fe rence s ( thi s ) ;
1 1 CheckBoxPreference

if (prefs . getBoolean ( ge t S t ring ( R . s t ring . pr_openmode ) , false ) )


openFi le ( FI LENAE ) ;

@ Ove r ride
pu l i c boolean onCreateOptionsMenu ( Menu menu )

menu . add (Menu . NONE , I DM_OPEN , Menu . NONE , " Open " )
. s e t i con ( R . drawale . i c_menu_open )
. setAlphabeticShortcut ( ' o ' ) ;
menu . add (Menu . NONE , I DM_SAVE , Menu . NONE , " S ave " )
. s e t i con ( R . drawale . i c_menu_save )
. setAlphabetic Shortcut ( ' s ' ) ;
menu . add (Menu . NONE , I DM_PRE F, Menu . NONE , " Sett ings " )
. se t i con ( R . drawale . i c_menu_pre ference s )
. s etAlphabet i c Shortcut ( ' t ' ) ;
menu . add (Menu . NONE , I DM_EXI T , Menu . NONE , " Exit " )
. se t i con ( R . drawale . i c_menu_ex i t )
. s etAlphabeticShortcut ( ' x ' ) ;
return ( supe r . onCreateOpt ionsMenu (menu ) ) ;

@ Ove rride
pul i c boolean onOpt ions i t emSelected (Menuitem item)
swi t ch ( item . geti temi d ( ) )
ca s e I DM OPEN :
openFi le ( FI LENAE ) ;
bre a k ;
c a s e I DM SAVE :
saveFile ( FI LENAE ) ;
break ;
case I DM PREF :
Intent intent

new Intent ( ) ;

intent . setCla s s ( this , Prefe rencesActivity . c l a s s ) ;


sta rtActivity ( intent ) ;
bre a k ;
ca s e I DM EXIT :
finish ( ) ;
brea k ;


de faul t :
return fal s e ;
return t rue ;

private void openFile ( S t r ing f i l eName )


t ry
InputS t ream inStream = openFi l e input ( FI LENAE ) ;
i f ( inStream

nul l )

InputS t reamReade r tmp


new InputS t reamReader ( inSt ream) ;
Buf fe redReade r reade r

new Buffe redReade r ( tmp ) ;

S t ring s t r ;
S t ringBuffer buffer

new S t ringBu ffer ( ) ;

whi l e ( ( s t r = reade r . readLine ( ) )

nul l )

buffer . append ( s t r + " \n " ) ;

inSt ream . close ( ) ;


mEdit . setText ( bu f fe r . toString ( } ) ;

catch ( Throwale t )
Toas t . makeText ( getApp l i cati onContext ( ) ,
" Except i on : " + t . toString ( ) , Toast . LENGTH_LONG )
. show ( ) ;

private void save File ( S t ring Fi leName )


t ry {
Output S t reamWriter outS t ream =
new Output S t reamWriter ( openFileOutput ( FI LENAE , 0 ) ) ;
out S t ream . write (mEdi t . getText ( ) . toString ( ) ) ;
out S t ream . close ( ) ;
catch ( Throwale t )
Toa st . makeText ( getApp l i cationContext ( ) ,
" Except i on : " + t . toString ( ) , Toast . LENGTH_LONG)

309

1 4

310
. s how ( ) ;

.
(. 1 4 .5).

Some text. . .
Sore text...

Sdve

0
Exlt

. 1 4.5. n - Chec koxPre ference

1 4. 2 . 3 . EditTextPreference
Adro i d
- EditText Prefe rence.
, .
,
-
.

<Edi tTex t P r e fe rence> 1 4. 8 .

< Prefe rence Screen


xmlns : andro id= " http : / / s chemas . andro id . com/ap k / r e s / andro i d " >

31 1


<CheckBoxPreference
android : key= " @ string/pr_ope ode "
android : t i t le= " Open f i l e "
android : summa ry= " To open f i l e at start appl i cation " / >
<Edi tTextPre ference
android : key= " @ s t ring/pr_s i z e "
android : t i t le="Text S i z e "
android : summa r y= " Set text s i ze "
android : de faul tVa lue= " l 4 "
android : di a l ogT itle="Ente r text s i z e ( from 1 0 to 3 2 ) " / >
< / Preference Sc reen>

onRe sume ( )
( 1 4.9).

@ Ove rr ide
pu ic void onResume ( )
supe r . onRe sume ( ) ;
SharedPrefe rences pre fs
Prefe renceManage r . get De fault SharedPrefe rence s ( thi s ) ;
1 1 Chec kBoxPre ference
if ( pre fs . getBoolean ( ge t S t ring ( R . st ring . pr_openmode ) , false ) )
openFi l e ( FI LENAE ) ;

1 1 EditText Pre ference


float f S i z e

Float . parseFloat (

prefs . get S t ring ( getSt ring ( R . st ring . pr_s i z e ) ,

"20 " ) ) ;

/ 1 EditText
mEdit . se tText S i z e ( fS i z e ) ;

.

(. 1 4 .6).
EditText Prefe rence
, .
,
.

1 4

312

. 1 4. 6 . n n Edi tText Prefe rence

1 4. 2 .4. ListPreference
L i s t P r e fe rence
.
.
,
SharedPrefe rence s .

.
: Regular, Bold, Italic, Bold+Italic.
L i s t Preference arrays.xml
res/values/. 1 4 . 1 .

< ?xml ve rsion= " . 0 " encoding= " ut f- 8 " ? >


<resource s >
< s t r ing-array name=" text_ styl e " >
< itern>Regular< / i tem>
< i t em>Bo ld< / i tem>
< i t ern> I t a l i c < / item>
< i t em>Bold+ I t a l i c < / itern>
< / s t r ing-array>
< / resource s >

313

preferences.xml n <ListPrefe rence>,


n , n
( 1 4 . 1 1 ) .

<Prefe rence Screen


xrnlns : android= "http : / / s chemas . android . com/apk/ res /android" >
<CheckoxPrefe rence
android : key= " @ st ring/pr_openmode "
android : t i t le = " Open f i l e "
android : surmnary="To open f i l e at start appl ication " / >
<EditTextPre ference
android : key= " @ string/pr_s i z e "
android : t i t le="Text S i z e "
android : surmnary= " Set text s i z e "
android : de faul tValue= " 1 4 "
android : di alogTit le="Ente r text s i z e ( from 1 0 t o 3 2 ) " / >
<List Pre ference
android : key= " @ string/pr_style "
android : t it le="Text Styl e "
android : surmnary= " Set text s t yle "
android : de faul tValue= " l "
android : ent ries= " @ a rray/ text_style "
android : entryValue s=" @ ar ray/ text_s t yl e "
android : dialogTitle="Choose text styl e " / >
< / P re ferenceS c reen>

1 4. 1 2 n onRe sume ( ) .

@Ove r ride
pulic void onRe sume ( )
supe r . onRe sume ( ) ;
SharedPrefe rences pre fs
PreferenceManager . getDefaultSharedPre ference s ( thi s ) ;
1 1 CheckoxPre fe rence
if ( pre fs . getBoolean ( ge t S t ring ( R . s t ring . pr_openmode ) , fa l se ) )
openFi le ( FILENAE ) ;

314

1 4
1 1 EditTextPrefe rence
float f S i z e

Float . pa rse Float (

prefs . get S t ring ( getSt ring ( R . s t ring . pr_s i z e ) , " 2 0 " ) ) ;


1 1 L i s t Prefe rence
St ring regul a r
int type face

prefs . ge t S t r ing ( ge t S t r ing ( R . s t ring . pr_styl e ) ,


Typeface . NORAL ;

i f ( regula r . contains ( " Bold" ) )


t ype face += Typeface . BOLD ;
!

i f ( regula r . contains ( " I t a l i c " ) )


type face += Typeface . I TAL IC ;

EditText

mEdi t . s etText S i z e ( fS i z e ) ;
mEdi t . s e tTypeface ( nul l , typeface ) ;

.
TextStyle
(. 1 4.7).
, ,
Cancel. .

Regu l a r
Bold

. 1 4.7. L i s t Prefe rence

315

1 4.2.5. RingtonePreference
Ringtone Prefe rence -
.
,
( 1 4 . 1 3 ) .

<Preference S c reen
xmlns : android= " http : / / s cherna s . android . com/ apk/ res / android" >
<CheckoxPrefe rence
android : key= " @ st r ing/pr_openmode "
android : t i t le= "Open f i l e "
android : swnma ry= " T o open f i l e a t start app l i ca t i on " / >
<EditText Prefe rence
android : key= " @ s t ring/pr_s i z e "
android : t i t le= "Text S i z e "
android : swnma ry= " Set text s i ze "
android : de faul tVa lue= " l 4 "
android : di alogT i t l e= " Enter text s i ze ( f rom 1 0 to 3 2 ) " / >
<List Pre ference
android : key= " @ s t ring /pr_styl e "
android : t i t l e = " Text S t y l e "
android : swnmary= " Set t e x t styl e "
android : de faul tValue= " l "
android : ent ries=" @ a r ray/ text_styl e "
android : entryValue s= " @ a r ray/ text_styl e "
android : dialogT i t l e= " Choose text styl e " / >
<Ringtone Prefe rence
android : key= " @ s t r ing/pr_tone "
android : t i t le= "Tone "
android : showDe fault= " t rue "
android : showS i l ent= " t rue "
android : swnmary= " Set tone ( on or o f f ) " / >
< / P referenceSc reen>

<Ringtone Pre fe rence>


(. 1 4. 8).
, ,
, .
<Ringtone Prefe rence>

1 4

316


Silent.
android : showS i l ent,

t rue,

Defa u l t ri ngtone

. 1 4.8.

Ringtone Prefe rence

1 4. 2 . 6 . PreferenceCategory
,
.
Preferences Framework ,
.
< Pre ferencecat egory> L-
.
,
< P re fe rence sc reen>, L-
<Prefe rencecategory>
<Preferences c reen>,
.
, ,
1 4. 1 4.

<Pre fe rence Screen


xmlns : andro id= " http : / / s chemas . andro i d . com/ap k / res / andro i d " >
< P re ferenceCategory android : t i t l e= " Open f i l e rnode prefe rences " >

31 7

<CheckBoxPrefe rence
android : key= " @ s t ring/pr_openrnode "
android : t itle= " Open f i l e "
android : sUI!U11a ry= " T o open f i l e at s t a r t appl ication " / >
< / Prefe renceCategory>
< P re fe renceCategory android : t it le= "Text p re fe rence s " >
<EditTextPrefe rence
android : key= " @ s t ring /pr_s i z e "
android : t itle="Text S i ze "
android : sUI!U11a r y= " Set text s i z e "
android : de faul tVa lue= " l 4 "
android : dialogTitle="Enter text s i ze ( from 1 0 t o 3 2 ) " / >
<ListPre fe rence
android : ke y= " @ string /pr_styl e "
android : t i t le= " Text Styl e "
android : sUI!U11a r y= " Set text s t yle "
android : de faultValue= " l "
android : entries= " @ a r ray/ text_styl e "
android : entryVa lue s= " @ a r ray/ text_styl e "
android : dialogT i t l e= " Choose text s tyle " / >
< / Pre fe renceCatego ry>
< Prefe renceCategory android : t itle=" Othe r Prefe rences " >
<RingtonePrefe rence
android : key= " @ st r ing/pr_tone "
android : t i tle= " Tone "
android : showDe faul t= " t rue "
android : showS i l ent= " t rue "
android : sUI!U11a r y= " Set tone ( on or o f f ) " / >
< / Pre fe renceCategory>
< / Pre ferenceScreen>

<Prefe rencecategory>
, .

, . 1 4.9.

1 4.2. 7. PreferenceScreen
< P reference Sc reen>
<Pre fe rence sc reen>.
<Pre fe renceScreen> .
<Prefe rence S creen>
n.

1 4

318

. 1 4. 9 . P r e f e renceCategory

preferences.xml
1 4. 1 5 .

< P re f e rence S c reen


xmlns : android= "http : / / s chema s . andro id . com/apk/ re s / andro id" >
< P refe renceCategory andro i d : t i t l e= " Open f i l e mode pre fe rence s " >
<Che c kBox P r e f e rence
andro id : ke y= " @ s t r ing/pr_openmode "
andro i d : t i t l e = " Open f i l e "
android : s lI\a r y= " T o open f i l e a t s t a r t app l i c a t i on " / >
< / Pre fe renceCa tegory>
< P refe renceCategory andro i d : t i t l e= " Text pre ference s " >
< P r e f e rence S c reen
andro i d : ke y= " @ s t r ing /pr_co l o r "
android : t i t l e = " Text Col o r "
android : s =a ry= " S e t t e x t c o l o r "
<Che c kBox P re f e rence
andro i d : key= " @ s t ring/pr_co l o r_ l a c k "
andro i d : t i t l e = " B l a c k "
andro i d : defaul tValue= " t rue "
andro i d : s lI\a r y= " Se t k c o l o r " / >

319

<CheckBoxPrefe rence
andro i d : key= " @ st ring/pr_color red"
android : t i t le="Red"
android : srunary= " Set red color " / >
<CheckBoxPre ference
android : key= " @ s t r ing/pr_color_green "
android : t it le= "Green"
android : sruna ry= " Set g reen colo r " / >
<CheckBox Prefe rence
andro id : key= " @ st ring/pr_color_lue "
andro id : t it le="Blue "
android : srunary= " Set lue color " / >
< / Prefe renceS c reen>
<Edi tText Prefe rence
android : key= " @ s t ring/pr_s i z e "
android : t i tle= " Text S i z e "
android : sruna ry= " Set text s i z e "
android : de faultValue= " 1 4 "
android : di alogT i t l e= " Enter text s i ze ( from 1 0 t o 3 2 ) " / >
<Li s t Pre ference
android : key= " @ s t r ing /pr_s t y l e "
android : t i tle= " Text S t y l e "
android : sruna ry= " Set text styl e "
android : de faul tVa lue= " l "
android : ent ries= " @ array/ text styl e "
android : ent ryVa lue s= " @ array/ text_styl e "
android : dialogT i t l e= " Choose text style " / >
< / Prefe renceCatego ry>
<Pre ferenceCategory android : t i t l e= " Othe r Prefe rences " >
<Ringtone Prefe rence
android : key= " @ s t ring/pr_tone "
android : t i tle= " Tone "
android : showDe fault=" t rue "
android : showS i l ent= " t rue "
android : srunary= " Set tone ( on or o f f ) '' / >
< / Prefe renceCategory>
< / PreferenceSc reen>


onRe sume ( ) Edi torActi vi ty.
,
.

1 4. 1 6.

onRe sume

( )

Edi torActi vity

1 4

320

@ Override
pul i c void onResume ( )
supe r . onRe sume ( ) ;
SharedPrefe rences prefs
PreferenceManager . getDe faul tSharedPre fe rences ( thi s ) ;
1 1 CheckoxPre fe rence
if ( pre fs . getBoolean ( getSt ring ( R . s t ring . pr_openmode ) , fals e ) )
openFi l e ( FILENAE ) ;

1 1 EditTextPrefe rence
float fS i z e

Float . parse Float (

pre fs . get S t ring ( getSt ring ( R . st ring . pr_s i z e ) ,

"20 " ) ) ;

1 1 CheckoxPre ference
11
int color

Co lor . BLACK ;

i f ( p re fs . getBoolean ( getString ( R . s t ring . pr_color_red ) , fals e ) )


color += Co lor . RE D ;
i f ( p re fs . getBoolean ( getSt ring ( R . s t r ing . pr_color g reen ) , fa l se ) )
color += Colo r . GREEN ;
i f ( p refs . getBoolean ( getSt ring ( R . s t r ing . pr_color lue ) , fal s e ) )
color += Colo r . BLUE ;
float f S i z e

Float . parse Float (


pre fs . get S t ring ( ge t S t ring ( R . st ring . pr_s i z e ) , " 2 0 " ) ) ;

1 1 L i s t Prefe rence
String regular = prefs . get S t ring ( getSt r ing ( R . st ring . pr_style ) ,
int type face

Type face . NORAL ;

i f ( regul a r . contains ( " Bold" ) )


t ype face += Type face . BOLD ;
i f ( regul a r . contains ( " Ital i c " ) )
t ype face += Type face . ITALI C ;


1 1

32 1

EditText

mEdi t . s e tText S i z e ( fS i z e ) ;
mEdi t . s e tTextColor ( co l o r ) ;
mEdi t . s e t T ype face ( nu l l ,

t ype face ) ;


Txt Color
. 1 4 . 1 .

. 1 4. 1 0 . Prefe rence S c reen


15

SQLite
-
SQLite
-.
- -
ndrid-,
. - ,
.
,
,
SQLite.

1 5. 1 . SQLite
Android ,
. Adroid
sq l ite ,
, SQL
SQLite.
, SQLite ,
/dataldatalpackage_name/ . SQLite (
, , )
. Android
SQLite.

1 5. 1 . 1 . :
SQLiteOpenHelper
Android SQLit eOpe nHe lper .
SQLit eOpene lper :

324

1 5

( ) - ;

onC reate

onUpgrade

( ) - .

, SQLiteopenHe lper.
,
.

,

. , . .
. ,
Contact:
pul i c static final S t r ing L_N = " contact " ;
pu l i c s t a t i c final S t r ing N
" first_name " ;
pu l i c static final St ring PHONE
"phone " ;

, SQLiteOpenelpe r,
asecolnn s , _I D,
.
ID INTEGER PRIARY AUTOINCREMENT.
AUTOINCREENT .
onCreate ( )
,
:
@ Over ride
pu l i c void onCreate ( SQLiteDatabase d ) {
d . execSQL ( " CREATE L
+ L_N
+

(_id INTEGER PRIARY AUTOINCREENT ,


+ COL PHONE +
) ; " ) ;
,

+ COL N +

onUpdate ( )
. onUpgrade ( ) ,
, ( DROP
L ) , onCreate ( )
, , :
@ Override
pul i c vo id onUpgrade ( SQLi teDatabase d , int oldVersion,
{
d . exec SQL ( " DROP L IF EXI ST S
onCreate ( d ) ;

+ L N ) ;

int newve rsion)

SQLite - t .

325

,
, .

1 5. 1 .2. :
SQLiteDatabase
Android SQLite
SQLit e Databa se. SQLiteDatabase ,
, , .
que ry ( ) :
Cursor que ry ( St r ing tal e , S t ring [ ] columns ,
St ring selection, S t r ing [ ] se lect ionArgs ,
St ring g roupBy, S t r ing having , S t r ing s ortOrde r )

que ry ( )

, ;

tale -

columns -

select ion - , WHERE (


WHERE ) . nul l ;

se lect ionArgs

groupBy ---, , GROUP (


GROUP ). GROUP , nu1 1 ;

having -

.
;

nul l

- ;

,
, nu1 1 ;

AVING) .

AVING

so rtOrde r - , ORDER (
ORDER ). nu l l .

Cursor, que ry ( ) ,
.
Cursor
getSt r ing ( ) , get int ( ) getFloat ( ) .
SQLite

insert ( ) :

long insert ( St ring tale , St ring nul l ColumnHack, ContentVa lue s va lues )

insert ( )

, ;

tale -

nul lCo lumnHack -

SQLite
, , -

326

1 5

, ,
nul l ;
( ),
-, -.
,
.

values -

insert ( )
.

_I D

- 1


update ( ) de lete ( ) :
int update ( St ring tale , ContentVa lues values ,
S t ring whe reClaus e , S t ring [ ] whe reArgs )
int de lete ( St ring tale , S t ring whe reClaus e , S t ring [ ] whereArgs )

SQL- WHERE
que ry ( ) .
.
,

.

1 5 . 2 . -
-
, , . - -

Android.

, :

-,

ContentProvide r;

-
,
.

-
- , ,
.
Content Provide r .
- ,

SQLite -
ContentRe s o lve r .

32 7

ContentRe s o lve r
( ) ndrid

ge tContentRe s o l ver

:
ContentRe s o lve r resolver

get ContentRe s o l ve r ( ) ;

ContentRe s o lver
-,
.
Android
, .
Content P rovi der,
.
,
content P rovide r . ,
ContentP rovider,
ContentRe s o lve r .
Cont ent P rovide r
ContentRe s o l ve r .

1 5. 2 . 1 .
- ,
- , -
. _ I D,
.
-
,
.
Cu r s o r, ,
, ,
. ,
. , , , .

1 5. 2.2. U RI
- URI (
u), .
, (
), U RI
. U RI " content :

1 5

328

n -n, n, n
URI . Andro id n URI n,
n. , , URI :
android . p rovide r . CallLog . Ca l l s . CONTENT_URI

URI -n.
ContentRe sol ve r URI n. URI , , ContentResolver
.

URI

, n . 1 5 . 1 .
content://com . s a m ples. contactprovider/contacts/1 33

'----v--1

'---------____..,

. 1 5. 1 .

URI

'--v-i

URI

D - n, , n
-n . n ;
D - URI , -.
n (
), u ;
D - , - , n
. -n
, URI . n
, , URI
, , : contacts /phot os contacts/bi rthday;
D D - . _ n.
, URI n :
content : / /com . samples . contactprovide r/ contacts

1 5 . 3 . -
-, n :
1 . .
2 . Cont entprovide r n

.
3 . -n n.

SQLite -

329

1 5. 3 . 1 . Con tentPro vider


ContentRe so lver,
U RI
. URI .
,
CONTENT_URI . URI
(. . -)
. :
content : / /com . samples . contactprovide r/ cont acts
content : / /com . samples . cont actp rovide r/contacts /photos

,
:
que ry ( )

contentProvide r,

- ;

insert

( ) - -;

update

( ) - -;

de lete

( ) - -;

getType ( )

- M I M E -.

onCreate ( ) ,
-,
SQLiteDataba s e :
p r ivate SQLiteDatabase d ;
@ Ove rr ide
pu l i c boolean onC reate ( )
d
( new ContactDbHe lper ( getContext ( ) ) ) . getWri tale Databa se { ) ;
return ( d
nul l )
fa l s e
t rue ;

que ry ( ) , insert ( ) , update ( ) , de lete ( ) ,


, content Provider,

SQLiteDataba se, . 15. 1.2. ,
- - .

:

que ry ( )

@ Override
pu l i c Cursor que ry ( U r i uri , S t r ing [ ] proj ect ion ,
S t ring s e l ection, S t r ing [ ] selectionArgs , S t r ing sort )
SQLit eQue ryBuilde r qb

Cont entProvider,

new SQLi teQue ryBuilder ( ) ;

330

1 5
qb . s etTal e s ( ContactDbHelpe r . TALE_NAE ) ;
qb . s et Proj ectionap (mContactMap ) ;
1 1
Cursor

qb . que ry ( d , proj ect ion , s e l ection, se lect ionArgs ,


nul l , nul l , s o rt ) ;

c . s e tNo t i f i cationUri ( getContext ( ) . getContentRe solve r ( ) , uri ) ;


re turn ;

insert

( )

@ Overr ide
pul i c Ur i insert ( Uri url , ContentVa lues i nVa lues )
ContentValues values

new ContentVa lue s ( inVa lues ) ;

1 1
d . insert (

long rowid

Cotact DbHe lpe r . TALE_NAE , ContactDbHe lpe r . NAE , va lues ) ;


1 1 URI rowid
Uri uri

ContentUri s . wi thAppendedid ( CONTENT_URI , rowid ) ;

getContext ( ) . getContentResolve r ( ) . noti fyChange ( ur i , nul l ) ;


return uri ;

insert ( ) - U RI
( ).
update ( )
( ) :

delete

@ Override
pul i c int update ( Uri uri , ContentVa lues values ,
S t r ing whe r e , St ring [ ] whe reArgs )

1 1
d . update (
int retVal
ContactDbHe lpe r . TALE_NAE , va lues , where , whe reArgs ) ;
getContext ( ) . getContentRe s olve r ( ) . noti fyChange ( ur i , nul l ) ;
return retVal ;

SQLite -

33 1

@ Overr ide
pu l i c int de lete ( Uri url , St ring where , S t ring [ ] whe reArgs )
int retVal

d . de lete ( ContactDbHe lpe r . TALE_NAE , whe re , whereArgs ) ;

getContext ( ) . getContentResolve r ( ) . noti fyChange ( ur l , nul l ) ;


return retVa l ;

n
.
n Content Provide r
ContentRe solver n n,
nn n .

1 5.3.2. -

Android -n,
, <provider>
AndroidManifest.xm l . -n,
, And roid,
n n .
n , n
<provide r> :
<provide r
andro id : name= " . ContactProvide r "
android : autho r i t i e s= " com . sample s . dcontact s . contactprovide r " >
< /provide r>

andro id : name -

n n ContentProvide r.
android : author i t i e s - authority URI,
-n.

<provide r>
n , ,
n, n . .

1 5.4. -
n -n n,
n: URI, n
, n n n n.

332

1 5

,
.
.

1 5.4.1 .
-,
ContentRe solve r . que ry ( ) Activity . managedQue ry ( ) :
Cursor que ry ( Uri uri , S t ring [ ] proj ection,
S t ring selection, S t ring [ ] s e lect ionArgs , Str i ng sortOrde r )
Cursor managedQuery ( Uri uri , St ring [ ] proj ection,
S t ring s e lect ion , S t ring [ ] s e lectionArgs , S t ring sortOrde r )


Cursor. managedQue ry ( )
cursor
.
.
:
- CONTENT_u,
Content Provide r .
URI,
ContentU ris . wi thAppendedid ( ) Uri . wi thAppendedPa th ( ) ,
URI .
ContentU r i s , Uri
;

U RI

, .

- ,
SQL- WERE (
WHERE ). nul l
, U RI .
,
.
. ,

-. -
_ I D,
.
_COUNT.
, SQL
oepaope ORDER . nul l ,

SQLite -

333

.
, SQLiteOpenHelper.
:
1 1 ,

pr ivate static final S t ring [ ] rnContent

new S t r ing [ ]

Cont actDbHe lpe r . I D ,


Contact DbHe lpe r . NAE ,
Contact DbHe lpe r . PHONE } ;
Cursor cursor
rnanagedQue ry (

Cursor curs or

Contact Provide r . CONTENT_URI , rnContent , nul l , nu l l , nul l ) ;

1 5.4.2.
cursor
. cursor
, Jv- I t e rator.
,
:
( ) - ;

rnoveToFi r s t

rnoveToLa s t

rnoveToNext ( )

rnoveToPrevious ( )

- ;

rnoveTo Pos i t ion ( )

- ;

get Pos i t i on ( )

( ) - ;

-
, . rnoveToNext ( )
t rue, , false,
;

- .


:
D

i s Fi r s t ( ) ;

i sLast ( )

i s BeforeFi rst ( ) ;

i sAfterLa s t ( ) .

1 5

334

1 5.4. 3 .
-,
- - ContentVa l ue s ,
-,
- .
ContentRe s o lve r . insert ( ) , URI
contentValues .
URI - . . URI -
.
U RI ,
. ,
:
ContentVa lues values

new ContentValues ( 2 ) ;


values . put ( Contact DbHe lpe r . NAE , textName . getText ( ) . toString ( ) ) ;
values . put ( Contact DbHe lpe r . PHONE , text Phone . getText ( ) . toString ( ) ) ;

get ContentRe solve r ( ) . insert ( Contact Provide r . CONTENT_URI , va lues ) ;

curso r . reque ry ( ) ;

1 5.4.4.
,
update ( ) . , :
ContentValues values

new ContentVa lue s ( 2 ) ;

va lues . put ( Cont act DbHe lpe r . NAE , textName . getText ( ) . toString ( ) ) ;
values . put ( ContactDbHe lpe r . PHONE , text Phone . getText ( ) . toString ( ) ) ;
getContentResolve r ( ) . update (
ContactProvider . CONTENT_URI , values ,

I D= "

i d , nul l ) ;

1 5.4.5.
,
( ) U RI . , :

ContentResol ve r .

de lete

getContentResolver ( ) . delete ( ContactProvider . CONTENT_URI ,


curso r . requery ( ) ;

I D= " + id, null ) ;

SQLite -

335

SQL- WHERE,
.
ContentRe sol ve r . de lete ( )

1 5. 5 .


.
1 1 .
,
.
Eclipse Create New Proj ect
:
] Proj ect name - contactEdi tor;
] Application name - Contacts Sample;
] Package name -

. samples . contacteditor;

] Create Activity - L i s t ContactActivity.


<provider> -.
1 5 . 1 .

< ?xml ve r s i on= " . 0 " encoding= " ut f- 8 " ?>


<mani fest xmlns : andro id= " ht tp : / / s chemas . android . com/ apk/ res /android"
pac kage= "com . s amples . dcontacts " >
<appl ication android : labe l= " @ s t ring /app_name " >
<provide r
android : name= " . ContactProvide r "
andro id : authori t i e s= " com . s amples . dcontact s . Contact Provide r " / >
<ac t ivity
android : name= " . ContactActivity"
android : labe l= " @ s t ring/ app_name " >
<intent - f i l ter>
<action android : name=" android . intent . action . AIN " / >
<category
android : name=" andro id . intent . category . LAUNCHER " / >
< / intent - f i l te r>

1 5

336
< /activity>
< / appl i cation>
< /man i fe s t >

mai n .xml 1 5 .2.

< ? xml ve rs ion= " l . O " encoding= "utf- 8 " ? >


<Re lat iveLayout
xmlns : andro id= " http : / / s chernas . android . com/ apk/ res /android"
android : ori entation="horizontal "
andro id : layout_width= " fi l l_pa rent "
android : layout_he i ght= " fi l l_pa rent " >
<TextVie1-1
android : id= " @ + id/narne "
android : layout_width= "wrap_content "
android : layout_hei ght= "wrap_content "
androi d : layout _a l i gnPa rentLeft= " t rue "
android : textS i ze= " l 8 sp " / >
<TextVi ew
android : id= " @ +id/phone "
android : layout_width= "wrap_cont ent "
android : layout_he i ght= "wrap_content "
android : layout_a l i gnPa rentRight= " t rue "
android : textS i ze= " 1 8 s p "
android : paddingRight= " l Opx " / >
< /Re lat iveLayout>


,
.
Cancel .
n 1 5 .3 .

< ? xrnl ve rs ion= " l . O " encoding= " ut f- 8 " ? >


<LinearLayout xmlns : andro id=" http : / / s chemas . android . com/ apk / r e s / andro id"
android : orienta tion= "ve r t i cal "
andro id : layout_wi dth= " f i l l_pa rent "
andro id : layout_he i ght=" wrap_content " >

SQLite - t

337

<Linea rLayout
android : orientation= " hori zonta l "
android : layout_width= " f i l l_parent "
android : layout_he ight= "wrap_content " >
<TextView
android : text= " @ string / f ield_name "
android : l a yout_width= "wrap_content "
android : layout_he i ght="wrap_content "
android : layout_a l i gnPa rentLe ft= " t rue " / >
<EditText
android : i d= " @ + id/name "
android : layout_width= " fi l l_pa rent "
android : layout_he ight= " wrap_content "
android : layout_a l i gnParentRight= " t rue " / >
< /Linea rLayout>
<Linea rLayout
android : o rientation= " ho r i z onta l "
android : layout_width= " f i l l_parent "
android : layout_he i ght=" wrap_content " >
<TextView
android : text= " @ s t r ing / f ield_phone "
android : layout_width= "wrap_content "
android : layout_he i ght="wrap_content "
android : l ayout_a l i gnPa rentLe ft= " t rue " / >
<EditText
android : id= " @ + id/phone "
android : l a yout_width= " fi l l_pa rent "
android : layout_he i ght= "wrap_content "
android : layout_a l i gnPa rentRight= " t rue " / >
< / Linea rLayout >
< / LinearLayout>

strings.xml n n n,
n ( n n
n n
). stri ngs.xml n 1 5 .4.

< ?xml ve rs ion= " l . O " encoding= " ut f- 8 " ?>


<resource s >
< s t ring name= " app_name " >Contacts from databa s e sample< / s t ring>
<string name="btn_ok" >OK< / s t ring>
< s t r ing name="btn_cance l " >Cance l < / s t ring>

1 5

338
< s t r ing name= " field_name " >Name : < / s t ring>
< s t r ing name= " field_phone " > Phone : < / s t ring>
< s t ring name= " t it l e_add" >Add new Contact< / s t r ing>
< s t r ing name= " t i t l e_edi t " >Edit Contact < / s t ring>
< s t ring name= " t i t l e de lete " > Delete this Contact ? < / s t r ing>
< s t ring name="menu_add" >Add< / s t r ing>
< s t ring name="menu_edi t " >Edi t < / s t ring>
< s t r ing name= "menu_de l e te " >De lete< / s t r ing>
< s t ri ng name=" toa s t_not i f y " > Please select Contact ! < / s t ring>
< / resources >

ContactDbHe lpe r, SQLiteOpenHe lpe r,


Contact .
oncreate ( )
.
ContactDbHe lpe r 1 5 . 5 .

pac kage com . samples . dcontact s ;


import android . content . ContentValue s ;
import android . content . Context ;
import andro id . databa s e . Cl!rso r ;
import andro id . databa s e . sqlite . SQLi teDatabase ;
import android . databa s e . sqlite . SQLi teOpene lpe r ;
import android . provide r . BaseCo lumns ;
pu l i c c l a s s ContactDbHelper extends SQLiteOpene lper
implements BaseColumns
pu l i c s t a t i c final S t r ing L N
pu l i c s t a t i c final St r ing N

" contact " ;

" fi r s t name " ;

pu l i c s tat i c final S t r ing PHONE

"phone " ;

pul i c Contact DbHe lper ( Context context )

supe r ( context , Contact Provide r . DB_CONTACT S , nul l ,

@ Ove rride
pul i c void onCreate ( SQLi teDatabase d )
d . exec SQL ( " CREATE L
+

+ L N

( _ id INTEGER PRIARY AUTOINCREENT ,

+ N + " ,

" + PHONE + " ) ; " ) ;

"

SQLite -
ContentVa1ues va1ues
va1ues . put ( NAE ,
va1ues . put ( PHONE ,

new ContentVa 1ues ( ) ;

" Jacob Ande rson " ) ;


"412412411 " ) ;

d . insert ( TALE_NAE , N , va 1ues ) ;


va 1ues . put ( NAE , " Emi 1y Duncan " ) ;
va 1ues . put ( PHONE ,

" 1 6 1 8 63 1 8 7 " ) ;

d . insert ( TALE_NAE , N , va 1ues ) ;


va 1ue s . put ( NAE , "Michae1 Fu1 1 e r " ) ;
va 1ues . put ( PHONE ,

"8 9 6 4 4 3 65 8 " ) ;

d . insert ( TALE_NAE , N , va1ues ) ;


va1ues . put ( NAE , " Ermna Greenman " ) ;
va1ues . put ( PHONE , " 9 6 4 9 9 0 5 4 3 " ) ;
d . insert ( TALE_NAE , N , va 1ues ) ;
va1ues . put ( NAE ,
va1ues . put ( PHONE ,

" Joshua Ha rrison" ) ;


" 7 5 928508 6 " ) ;

d . insert ( TALE_NAE , N , va1ues ) ;


va1ues . put ( NAE , "Madi son Johnson" ) ;
va 'L ues . put ( PHONE , " 9 5 0 2 8 5 7 7 7 " ) ;
d . insert ( TALE_NAE , N , va1ues ) ;
va1ues . put ( NAE , "Matthew Cotrnan " ) ;
va1ues . put ( PHONE ,

" 68 7 6 9 9 9 9 9 " ) ;

d . in s e rt ( TALE_NAE , N , va 1ues ) ;
va1ues . put ( NAE , "01ivia Lawson " ) ;
va1ues . put ( PHONE ,

" 1 6 1 8 63 1 8 7 " ) ;

d . insert ( TALE_NAE , N , va1ues ) ;


va 1ues . put ( NAE , "Andrew Chaprnan " ) ;
va1ues . put ( PHONE , " 5 4 6 5 9 9 64 5 " ) ;
d . insert ( TALE_NAE , N , va1ues ) ;
va1ues . put ( NAE , " Danie1 Honeyrnan " ) ;
va1ues . put ( PHONE ,

"87 654 5644 " ) ;

d . insert ( TALE_NAE , N , va 1ues ) ;


va1ues . put ( NAE , " I sabe 1 1 a Jackson " ) ;
va1ues . put ( PHONE ,

" 90 7 8 6 8 7 5 6 " ) ;

d . insert ( TALE_NAE , N , va 1ues ) ;

339

340

1 5
values . put ( NAE ,

" W i l l iam Patterson " ) ;

values . put ( PHONE ,

" 68 7 6 9 9 6 93 " ) ;

d . ins ert ( TALE_NAE , N , va lues ) ;


values . put ( NAE ,

" Joseph Godwin " ) ;

values . put ( PHONE ,

" 9 6 5 4 67 5 7 5 " ) ;

d . ins ert ( TALE_NAE , N , va lues ) ;


values . put ( NAE , " S amantha Bush " ) ;
va lues . put ( PHONE ,

" 90 7 8 6 5 64 5 " ) ;

d . insert ( TALE_NAE , N , va lues ) ;


values . put ( NAE , " Chr i s t ophe r Gateman " ) ;
values . put ( PHONE , " 8 9 6 8 7 4 5 5 6 " ) ;
d . insert ( TALE_NAE , N , values ) ;

@ Ove rride
pu i c void onUpgrade (
SQLiteDatabase d , int oldVers ion, int newVe r s ion)
d . execSQL ( " DROP L I F EX I ST S
+ L_N ) ;
onCreate ( d ) ;

ContactProvide r, Content Provide r,


Contacts.
ContactProvide r 1 5 .6.

pac kage corn . sample s . dcontacts ;


irnport j ava . ut i l . Hashap ;
irnport android . content . Content Provide r ;
irnport android . content . ContentUri s ;
irnport andro id . content . ContentValue s ;
irnport android . content . Ur iMatche r ;
irnport android . database . Curso r ;
irnport android . databa s e . SQLExcept ion ;
irnport android . databa s e . sqlite . SQLi teDataba se ;
irnport android . databas e . sqlite . SQLiteQue ryBuilde r ;

SQLite -

34 1

import andro id . net . U r i ;


import andro id . text . TextUt i l s ;
pu i c class ContactProvide r extends ContentProvide r
" contact s . d " ;

pu l i c s t a t i c f ina l S t r ing DB_CONTACTS


pu l i c static final Uri CONTENT URI

Uri . parse (

" content : / /com . samples . dcontacts . contactprovider / contact " ) ;


pul i c static f inal int URI CODE

1;

pu l i c static final int URI_CODE_I D

2;

private stat i c final UriMatcher mU r iMatche r ;


private static Hashap<St ring , String> mContactMap ;
private SQLite Database d ;
static
mUr iMat che r

new UriMatche r ( U riMatche r . NO ) ;

mU riMatche r . addURI ( " com . samples . dcontacts . contactprovide r " ,


Conta ctDbHelpe r . TALE_NAE , URI_CODE ) ;
mU riMatche r . addURI ( "com . samples . dcontacts . contactprovide r " ,
ContactDbHe lpe r . TALE_NAE + " / # " , URI_CODE_I D ) ;
mContactMap

new Hashap<S t ring , String> ( ) ;

mContactMap . put ( ContactDbHelpe r . I D , ContactDbHe lpe r . I D ) ;


mContactMap . put ( ContactDbHe lper . NAE , Contact DbHe lper . NAE ) ;
mContactMap . put ( Conta ctDbHe lper . PHONE , Contact DbHelpe r . PHONE ) ;

pu l i c S t ring get DbName ( )


return ( DB_CONTACT S ) ;

@ Ove rride
pu l i c boo lean onC reate ( )
d

( new Contact DbHe lpe r ( getContext ( ) ) ) . getWr italeDa taba se ( ) ;

return ( d

nul l )

fa lse

t rue ;

@ Ove rride
pu l i c Cursor que ry ( U ri url , S t ring [ ] proj ection,
String se lection, S t r ing [ ] selectionArgs , S t r ing sort )

1 5

342
S t r ing o rde rBy ;
i f ( TextUt i l s . isEmpty ( so rt ) )
orde rBy = ContactDbHe lpe r . NAE ;
else
sort ;

orderBy

Cu rsor

d . que ry ( Cont act DbHe lpe r . TALE_NAE ,


proj ection, selection, select i onArgs ,
nul l , nul l , o rde rBy ) ;

c . s e tNot i f icat ionUri ( getContext ( ) . getContentRe solve r ( ) , ur l ) ;


return ;

@ Ove r ride
pu l i c Uri insert ( U ri url , ContentVa lue s inVa lue s )
ContentVa lues va lues
long rowid

new ContentValues ( inVa lues ) ;

d . insert (

ContactDbHe lpe r . TALE_NAE , ContactDbHe lpe r . NAE , va lues ) ;


i f ( rowid > 0 )
Uri u r i

ContentU r i s . wi thAppendedid ( CONTENT_UR I , rowid ) ;

getContext ( ) . getContentResolve r ( ) . noti fyChange ( u r i , nul l ) ;


return uri ;
else
throw new SQLException ( " Fai led to insert row into

@ Ove rride
pu l i c int de lete ( Uri url , S t ring whe re , S t ring [ ] whe reArgs )
int retVal
whereArgs ) ;

d . de lete ( ContactDbHe lpe r . TALE_NAE , whe re ,

getContext ( ) . getContentRe solve r ( ) . noti fyChange ( u r l , nul l ) ;


return retVal ;

+ ur l ) ;

SQLite -

343

@ Ove rride
pu l i c int upda te ( U r i ur1 , ContentVa 1ues va1ue s ,
S t ring whe re , S t r ing [ ] whe reArgs )
int retVa1

d . update ( Cont actDbHe 1pe r . TALE_NAE , va1ue s ,


whe re , whe reArgs ) ;

getContext ( ) . getContentRe so1ve r ( ) . noti fyChange ( u r 1 , nu1 1 ) ;


return retVa1 ;

@ Ove rride
pu l i c S t ring getType ( U r i uri )
return nu1 1 ;

NewContactActivity
- Add, Edit Delete - ,

NewcontactActivity 1 5 . 7.

pac kage com . samp1e s . dcontact s ;


import android . app . A1ertDia1og ;
import android . app . Li s tAct ivi t y ;
import android . content . ContentVa1ue s ;
import android . content . Dia1og i nte rface ;
import android . database . Cursor ;
import android . os . Bund1e ;
import android . view . Layout inf1ate r ;
import andro id . view . Menu ;
import android . view . Menui tem;
import andro id . view . View ;
import android . widget . EditText ;
import andro id . widget . Li s tAdapte r ;
import andro id . widget . S imp1eCursorAdapte r ;
import andro id . widget . Toas t ;
pu l i c c 1 a s s ContactActivity extends L i s tActivity
private s t a t i c fina1 int I DM ADD
private s t a t i c fina1 int I DM EDIT

101 ;
102 ;

private static fina1 int I DM DELETE = 1 0 3 ;

1 5

344
p r ivate Cu rsor mCurso r ;
private Lis tAdapter mAdapter ;
private s t a t i c fina l St ring [ ] mContent

new S t ring [ ]

Cont act DbHelpe r . _I D , ContactDbHe lpe r . NAE ,


ContactDbHe lpe r . PHONE } ;
@ Ove rride
pu l i c void onCreate ( Bundle savedins tance State )
supe r . onCreate ( savedins tanceState ) ;
mCursor

managedQue ry (

Contact Provide r . CONTENT_URI , mCont ent , nu l l , nul l , nul l ) ;


mAdapter

new S impleCurso rAdapter ( th i s ,


R . layout . row, mCu r s o r ,
new String [ ]
new int [ ]

{ ContactDbHelper . NAE , ContactDbHelper . PHONE } ,

{ R . id . name , R . id . phone } ) ;

s e t L i s tAdapter (mAdapte r ) ;

@ Ove r ride
pu l i c boolean onCreateOpt ionsMenu ( Menu menu )
menu . add ( Menu . NONE , I DM_ADD , Menu . NONE , . R . s t r ing . menu_add )
. s e t l con ( R . drawal e . i c_menu_add )
. s etAlphabet i c S hortcut ( ' a ' ) ;
menu . add (Menu . NONE , I DM_EDIT , Menu . NONE , R . s t r ing . menu_edi t )
. s e t l con ( R . drawal e . i c_menu_edi t )
. s etAlphabe t i cShort cut ( ' e ' ) ;
menu . add (Menu . NONE , I DM_DELETE , Menu . NONE , R . s t ring . menu_de lete )
. s e t i con ( R . drawal e . i c_menu_de lete )
. s etAlphabet i c Shortcut ( ' d ' ) ;
return ( supe r . onCreateOpt i onsMenu (menu ) ) ;

@ Ove rride
pu l i c boo lean onOptions i temSelected (Menultem i tem)
f inal long id

this . get Selecteditemid ( ) ;

swi tch ( i tem . getltemld ( ) )


case I DM_ADD :

Cal lAddContactDia log ( ) ;


brea k ;

345

SQLite -
case I DM EDIT :
i f ( id > 0 )
Ca l lEdi tContactDialog ( i d ) ;
else

Toa s t . rnakeText ( th i s , R . s t r ing . toas t_no t i f y ,


Toa st . LENGTH_SHORT )
. show ( ) ;
bre a k ;
c a s e I DM DELETE :
i f ( id > 0 )

Ca llDeleteContactDia log ( id ) ;
else
Toast . rnakeText ( this , R . s t r ing . toa s t_not i fy ,
Toa s t . LENGTH_SHORT )
. show ( ) ;
brea k ;
return ( supe r . onOpt i ons i ternSe lected ( itern) ) ;

private vo id Cal lAddContactDia log ( )


Layout inflater inflate r
View root

tayoutinflater . frorn ( th i s ) ;

inflate r . inflate ( R . layout . dialog, nul l ) ;

final EditText textNarne

( Edi tText ) root . findViewByid ( R . id . narne ) ;

final Edi tText text Phone


( Edi tText ) root . f indVi ewByid ( R . id . phone ) ;
Ale rtDia log . Bu i lder

new Ale rtDialog . Builde r ( thi s ) ;

b . s e tView ( root ) ;
b . s e tT i t le ( R . s t ring . t i t l e_add ) ;
b . setPo s i t iveButton (
R . s t ring . btn_o k , new Dia loginterface . OnC l i c kLi s tene r ( )
pu ic void onCl ick ( Dialoginterface di alog , int whi chutton)
ContentVa lues va lues

new ContentVa lues ( 2 ) ;

va lue s . put ( ContactDbHe lper . NAE ,


textName . getText ( } . toSt ring ( ) ) ;
va lues . put ( ContactDbHe lper . PHONE ,
text Phone . ge tText ( ) . toString ( ) ) ;

1 5

346

getContentRes o lve r ( ) . insert ( Conta ct Provider . CONTENT_URI ,


values ) ;
mCursor . reque ry ( ) ;
}) ;
b . s etNegat i veButton (
R . string . btn_cancel , new Dialoginte rface . OnClickListener ( )
pulic void onCl ick ( Dia loginterface dia log , int whichutton )

{}

}) ;
. show ( ) ;

private void Cal lEditContactDialog ( fina l long i d )

Layout inflater . f rom ( th i s ) ;

Layout inflater inflater


View root

inflat e r . inflate ( R . layout . di a log, nul l ) ;

final EditText textName

( Edi tText ) root . findViewByid ( R . id . name ) ;

final EditText text Phone


( Edi tText ) root . f indViewByid ( R . id . phone ) ;
mCu rsor . moveTo Pos i t ion ( th i s . get S e lectedi temPo s i t ion ( ) ) ;
textName . s etText (mCursor . get S t r i ng ( l ) ) ;
text Phone . s etText ( mCurso r . get S t r ing ( 2 ) ) ;
AlertDia log . Bui lde r

new Ale rtDi alog . Bu i l de r ( thi s ) ;

b . s e tView ( root ) ;
b . setTitle ( R . s tring . t i tle_edi t ) ;
b . s e t Pos i t i veButton (
R . s t ring . btn_o k , new Dia loginterface . OnC l i c kL i s tene r ( )
pulic vo id onCl ick ( Dialoginterface dia log , int whichutton)
ContentVa lues value s

new ContentVa lues ( 2 ) ;

value s . put ( Cont actDbHelpe r . NAE ,


textName . getText ( ) . to S t r i ng ( ) ) ;
values . put ( Contact DbHe lpe r . PHONE ,
text Phone . ge tText ( ) . toString ( ) ) ;
getContentRe solve r ( ) . update (
Contact Provide r . CONTENT_URI , va lue s ,
mCursor . requery ( ) ;

I D= " + i d , nul l ) ;

34 7

SQLite -
b . s etNegativeButton (

R . string . btn_cancel , new Dialoginterface . OnClickListener ( )


pulic void onClick ( Dialoginterface dialog , int whichutton )

{}

b . show ( ) ;

private vo id Ca l l DeleteContactDialog ( f ina l long i d )


Ale rtDialog . Builde r

new Ale rtDialog . Bu i lder ( this ) ;

b . setTitle ( R . s t ring . t i t l e_de lete ) ;


b . s e t Pos i t iveButton (
R . s t ring . btn_o k , new Dialoginterface . OnCl ickLi s tene r ( )
pulic void onCl ick ( Dialoginterface dialog , int whichutton )
getContentRe s o lve r ( ) . de lete (
Contact Provide r . CONTENT_URI ,

I D= "

id, nul l ) ;

mCursor . reque ry ( ) ;

b . s etNegativeButton (
R . st ring . btn_cancel , new Dialoginterface . OnCl ickLi s tener ( )
pulic void onCl ick ( Dia loginterface dialog , int whichutton )

{}

b . show ( ) ;

.

onCreate ( ) ContactDbHe lper, Contacts
,
. 1 5 .2 .
,
,
, . 1 5 .3 .

1 5

348

. 1 5. 2 .

. 1 5.3. ,

16

,

- ndrid-.
, : , , ,
, , . .
res/ assets/.
, .
:
Ll

.
( res/)
;

R,

Ll , assets/ (

),
.

As s etanage r

,
ndrid-, ,
.
,
, .

1 6 . 1 .
Android ,
.
Ll -

,
.

1 6

350

n
RGB lh- ( 6).

n
, n
L-: <>, <i> <u> . ,
L- ,
.

w .

,
n n :

: * .png (
nn n ), * .j pg * .gif;
- ,
. n
res/values/;
Paint Drawale

Nine Patch - PNG, .


Android NinePatch n n
n, . .

Android n
. ,
nn , n n.

n n L
.

L- .

.
- n . ,
. n
.

, .
n , n , n Andro id,
Theme . dialog , n
.

1 6 . 2 .
3 , n
n n res/ n. Adroid SDK
aapt n .

351

n n n
.
LJ res/an i m/ - .
LJ res/drawa\e/ - .
LJ resllayout/ - L- .
LJ res/values/ - L-, n

. , res/
.
n , n
:

arrays.xml - ;

colors.xml - ;

d i mens.xml - ;

strings.xm l - ;

styles.xml - .

LJ res/xm l/ - n L- ,

n.
LJ res/raw/ - n , n n

1 6 . 3 .
L- ( )
. n
( ),
n , n, .
n, , n
, ,
:
android : textCo lor= " @ color/opaque_red"

n n @ ,
- n n - .
n, n
n.
n :
andro id : textColor= " @ andro id : color/opaque_red"

1 6

352

1 6 .4.

R ,
. R
, ,
Android,
. R :
R . anim -

res/an im/;

R . array -

res/values/;

arrays.xml
res/values/;

R . bool -

R . color -

colors.xm l res/values/;

R . dimen -

d imens.xm l res/values/;

R . drawale -

res/drawa\e/;


L- res/layout/;

R . id -


arrays.xm l res/values/;
R . intege r -

R . layout R . raw -

res/layout/;

res/raw/;

R . s t r i ng -

R . style -

R . xml -

strings.xm l res/val ues/;

sty\es.xml res/values/;

res/xml/.


,
. :
R . resource_type . re source_name

.
andro id . R. ,
:
andro id . R . drawale . sym_de f_app_icon

:
andro id . R . s tyle . Theme_Black

353

1 6.4. 1 .

, Eclipse :
D Project name -

S impleValue s ;

Application name - Re source


D Package name -

S imple;

com . sampl e s . s implevalue s ;

D Create Activity - S impleVa luesActiv i ty.

res/values/
strings.xm l . L- :
D arrays.xm l - ;
D colors.xm l - ;
D d imen .xm l - ;
D drawa\es.xm l - .

,
1 6. 1 -1 6 . 5 .

< ?xml ve rs ion= " l . O " encoding= " ut f - 8 " ? >


< re source s >
< s t r i ng-array name=" names " >
< i t em>Andrew< / item>
< i t em>He len< / i tem>
<item> Jack< / i t em>
< / s t r ing-array>
< i ntege r-array name= "digi t s " >
< i t em> l 9 9 9 < / i tem>
< i t em> 2 0 0 2 < / i tem>
< i tem>2 0 1 0 < / i tem>
< / intege r-array>
< / res ources >

< ? xml ve rs ion= " l . O " encoding= " ut f- 8 " ?>


<resource s >
<color name=" textColo r " > # O O O O FF</color>

354

1 6
<color name= "backg roundCo l o r " > # FFO O O O < / col or>

< / re s ources >

< ? xml ve rs i on= " l . O " encoding= " ut f - 8 " ?>


< resource s >
<dirnen name= " t ext Point S i z e " > l 8pt</dirnen>
< / resources >

< ?xml ve r s i on= " l . O " encoding= " ut f- 8 " ?>


< resource s >
<drawale name= " g rayDrawale " > # DDD< /drawale>
< / resources >

< ? xml ve rsion= " l . O " encoding= " ut f - 8 " ?>


< resource s >
< s t r i ng name= " app_name " >Re s ource Sample< / s t ring>
< s t r ing name= " s orne_text " > S orne Text < / s t ring>
< / re s ource s >


.
mai.xml 1 6.6.

< ? nl ve rs ion= " l . O " encoding= " ut f - 8 " ?>


<LinearLayout xrnlns : android= " http : / / schernas . android . com/ apk / re s / andro id"
andro id : orient a t i on= "ve rt ical "
andro id : layout_width= " fi l l_parent "
andro id : layout_he ight= " fi l l_parent " >
<Linea rLayout
android : layout_width= " wrap content "
android : layout_height="wrap_content " >
<TextView
android : layout_he ight=" wrap_content "
android : text= " S t r i ng array : "

355

android : l ayout_width= "wrap_content "


android : paddingRi ght = " Spx "
android : textCo lor= " @ color/ textColor" / >
<TextView
android : id= " @ +id/text_st rings "
android : l ayout_wi dth= "wrap_content "
android : layout_height="wrap_content "
android : padding= " Spx "
android : textColor= " @ color/textColo r " / >
< / Li nearLayout >
<LinearLayout
android : layout_width= " wrap content "
android : layout_he ight= "wrap_content " >
<TextView
android : layout_he ight="wrap_content "
android : text= " Int array : "
andro id : l ayout_width= "wrap_content "
android : paddingRight= " 2 0px "
android : padding= " Spx "
android : textCo lor= " @ color/textColor " / >
<TextView
android : id= " @ +id/ text_digi t s "
android : l ayout_wi dth= "wrap_content "
android : l ayout_he ight="wrap_content "
android : textColor= " @ color/ textColo r " / >
< / LinearLayout >
<LinearLayout
android : layout_width= " wrap content "
android : layout _he ight= "wrap_content " >
<TextView
android : id= " @ + id/text_style "
android : l ayout_width= "wrap_content "
android : l ayout_he ight="wrap_content " / >
< / Li nea rLayout >
< / LinearLayout >

S impleValuesActivity n
n n n
R. n 1 6.7.

356

1 6

package com . samples . s impleva lues ;


import android . app . Activi t y ;
import android . g raphics . drawale . Co lorDrawal e ;
import android . os . Bundle ;
import andro id . view . Window ;
import android . widget . TextView;
pul i c class S impl eVa luesActivity extends Act ivity
@ Ove rride
pul i c void onCreate ( Bundle s avedinstance S tate )
supe r .onCreate ( savedinstance State ) ;
setContentView ( R . layout . main ) ;
final TextView text St rings
( TextView ) findVi ewByid ( R . id . text_s t rings ) ;

1 1 res /value s / a rrays . xml


S t r i ng [ ] names
;

for ( int i

getRe sources ( ) . ge t S t r ingArray ( R . a r ray . names ) ;


i < names . lengt h ;

text S t r i ngs . append ( "Name [ " + i +

" + names [ i ] + " \n " ) ;

final TextView text Digits


( TextView ) findViewByid ( R . id . text_digits ) ;

1 1 re s /va lue s / a r rays . xml


i nt [ ] digits
for ( int i

getResources ( ) . ge t i ntArray ( R . a r ray . digi ts ) ;


;

i < digit s . lengt h ;

text Digi ts . append ( " Digi t [ " + i +

{
" + digits [ i ] + " \n " ) ;

1 1 ,
final TextView textStyle
( T extView ) fi ndVi ewByid ( R . id . t ext_style ) ;

1 1 res /value s / s t rings . xml


t ext Style . s etText (
getRe s ources ( ) . getText ( R . s t ring . some_text ) ) ;

357

/ 1 res /va lues /colors . xml


textStyle . s etTextCo lor (
getRe s ource s ( ) . getColor ( R . colo r . textColor ) ) ;
/ 1 res /values /dimen . l
textStyle . setText S i ze (
getRe s ources ( ) . get Dimens ion ( R . dimen . textPointS i z e ) ) ;
/ 1 res /values /colors . xml
textStyl e . s etBackg roundColor (
getResources ( ) . getColor ( R . colo r . backg roundColo r ) ) ;
/ 1
/ 1 res/value s /drawae s . xml
Window w = this . getWindow ( ) ;
w . s e tBackgroundDrawale (
( Col orDrawale ) getResources ( ) . get Drawale (
R . drawae . grayDrawale ) ) ;


, . 1 6. 1 .

. 1 6. 1 .

1 6

358

1 6.4. 2.
res/raw/ ,

" " . , -
, .

-, 14. ,
( ), 1 4, ,
res/raw/, ,
,
.

res/raw/, :
D Proj ect name -

ContactLauncher;

D Application name - Contact


D Package name -

Launche r Sample;

. samp l e s . contact launche r;

D C reate Activity - ContactLaunche rAct ivity.

mai .xml
1 6. 8 .

extView,

< ?xml ve r s i on= " l . O " encoding= " ut f- 8 " ?>


<Linea rLayout xmlns : andro id= " http : / / s chema s . android . com/ apk / re s / andro id"
andro id : ori entat ion= " ve r t i ca l "
andro id : layout_width= " f i l l_pa rent "
android : layout_he ight= " fi l l_pa rent "
android : gravity= " cent e r " >
<TextView
andro id : id= " @ + id/ text "
android : layout_he ight="wrap_content "
android : text= " @ s t ring / he l l o "
android : la yout_width= "wrap_content "
android : gravi t y= " l e ft l cente r " / >
< / LinearLayout>

,
14. ,
, 1 6 .9.

359

package com . sample s . raw ;


import j ava . io . Data inputSt ream ;
import j ava . io . I nput St ream;
import android . app . Activi t y ;
import android . os . Bundle ;
import android . widget . TextView ;
pul i c c l a s s RawAc t ivity extends Act ivi ty
@ Ove rride
pul ic void onC reate ( Bundle s avedinstance State )
supe r . onCreate ( savedinstance State ) ;
setContentView ( R . layout . main ) ;
final TextView text
InputS t ream i File

( TextView ) findViewByid ( R . id . text ) ;


getRe source s ( } . openRawRe source ( R . raw . f i l e ) ;

t ry {
S t r ingBuffer sBuffer

new S t r i ngBuffe r ( ) ;

Dat a i nput S t ream dat a i O = new Datainput S t ream ( i File ) ;


S t r i ng s t rLine

nul l ;

whi le ( ( s t rLine=da t a i O . readLine ( ) )

nul l ) {

sBuffe r . append ( s t rLine + " \n " ) ;

dat a i O . close ( ) ;
i F i l e . close ( ) ;
text . s e tText ( sBuf fe r . toString ( } ) ;
catch ( Except ion )
text . s etText ( " E rror loading f i l e :

+ e . getMe s s age ( ) ) ;

.

, . 1 6.2.

1 6

360

. 1 6.2. res/raw/

1 6 .4. 3 . XM L

L-, res/layouts/.
L-
. res/menu/.
L- :
- ;

<menu>

<group>

< i t em>

, ;

- , .

< itern> <group> <group>.


, .
XML
, . 1 0. 1. 1 . Ecl ipse
Create New Proj ect :
D Project -

I conenuApp;

D Applicatio D Package -

Load Menu from resource;

com . samples . re smenuxml ;

D Create Activity - Re sMenuXmlAct ivity.

361

L-, ,
- Open, Save, Edit, Help Exit - ,
. 1 0. 1. 1 , options.xm l
res/menu/ . options.xm l
1 6 . 1 0 .

<menu xmlns : android= " http : / / s chernas . android . com/ap k / re s / androi d " >
< i tern
android : id= " @ + id/ open "
android : t i t le= " Open "
android : icon= " @drawale / i c_rnenu open"
android : orde r i nCategory= " l " / >
< i tern
android : id= " @ + id / s ave "
android : t i t l e = " Save "
android : i con= " @drRwa l e / i c rnenu save "
android : orde r i nCategory= " 2 " / >
< i t ern
android : id= " @ + id/edit "
android : t i tle= "Edi t "
android : i con= " @drawa l e / i c rnenu edi t "
android : orde r i nCategory= " " / >
< i tern
android : id= " @ + id/he lp "
android : t i t le="Help"
androi d : icon= " @drawale / i c_rnenu he lp"
android : orde r i nCategory= " 4 " / >
< i tern
android : id= " @ + id/ex i t "
android : t i t le= "Exi t "
android : icon= " @drawale / i c rnenu ex i t "
android : orderinCategory= " 5 " / >
< /rnenu>


1 6 . 1 1 .

TextView

< ? Xml ve r s ion= " l . O " encoding= " ut f - 8 " ? >


<LinearLayout xmlns : andro i d= " http : / / s cherna s . andro i d . com/ apk / re s /andro i d "
android : orienta t i on= " ve r t i ca l "

1 6

362
android : layout_width= " f i l l_pa rent "
andro id : layout_he i ght= " fi ll_parent " >
<TextView
andro id : layout_width= " f i l l_parent "
android : layout_he ight = " wrap_content "
android : text = " Press ENU button . .
android : g ravit y= " cente r "
android : tex t S t yle= "bold" / >
< / L inearLayout>


, 1 .
onCreateOpt i onsMenu ( ) L
, :
@ Ove r r ide
pu l i c boolean onC reateOp t ionsMenu ( Menu menu )
ge tMenuinflate r ( ) . inflate ( R . menu . opt ions , menu ) ;
return t rue ;

L-
, , , .
R ,
, .
onOpt ions l t emSele cted ( ) ,
, :
@ Ove r r ide
pu l i c boolean onOp t i ons i temS e lected ( Menui tem i tem)
switch ( i tem . geti temid ( ) )
case R . id . open :
brea k ;
case R . id . s ave :
brea k ;
defaul t :
return fa l s e ;

return t rue ;

363


1 6 . 1 2 .

Re sMenuXmlActivity

package corn . sample s . re srnenuxml ;


irnport android . app . Ac t ivi t y ;
irnport android . os . Bundle ;
irnport android . view . Gravit y ;
irnport android . view . Menu ;
irnport android . view . Menui tern;
irnport android . widget . Toas t ;
pu l i c c l a s s Re sMenuXmlActivity extends Activi t y
@ Ove r ride
pu i c void onCreate ( Bundle s avedins tance State )
supe r . onCreate ( savedins tanceState ) ;
set Cont entView ( R . layout . rna in ) ;

1 1 L-
@ Ove r r ide
pu l i c boolean onCreateOptionsMenu ( Menu rnenu )
ge tMenuinflate r ( ) . inflate ( R . rnenu . options , rnenu ) ;
return t rue ;

@ Ove r ride
pu i c boolean onOption s i ternSelected ( Menu i tern itern )
Cha r Sequence rne s s age ;
swi tch ( itern . geti ternid ( ) )
ca s e R . id . open :
rne s s age

" Open i tern selected " ;

brea k ;
case R . id . s ave :
rne s sage

" Save i tern s e lected " ;

brea k ;
case R . id . help :
rne s s age
brea k ;

" He lp i tern se lected " ;

364

1 6
case R . id . edit :
me s sage

"Edit i tem s e lected " ;

brea k ;
case R . id . exit :
me s s age

"Exit i tem s e l ected " ;

brea k ;
de faul t :
return fa l s e ;
Toa s t toast

Toa s t . ma keText ( thi s , me s sage , Toas t . LENGTH_SHORT ) ;

toa s t . se tGravi ty ( Gravi ty . CENTER , , 0 ) ;


toast . show ( ) ;
return t rue ;

.
L- ,
(. 1 6 .3 ) .

Open

5a'le

0
Exlt

. 1 6. 3 . , L-

1 6.4.4. L-
Adroid L-
. -

365

L- ,
res/xml/,
.
L-
. Ec l i pse ,
, L-. New And roid Proj ect
:
D P roj ect name -

F i l e s_Xrnl ;

D Application name - XLRe s ource


D Package name -

Sample;

. samples . resxn11 ;

D Create Activity - Re sXrnlAct ivity.

res/ xm l/,
L- . ,
,
contacts.xm l . contacts .xm l
1 6. 1 3 .

<contacts>
<contact f i r s t_name=" Jacob " l a s t_name="Ande rson" phone= " 4 1 2 4 1 2 4 1 1 " / >
<contact f i rst_name= " Emi l y " last_name=" Duncan " phone= " l 6 1 8 6 3 1 8 7 " / >
<contact f i r s t_name= "Michae l " l a s t_name= " Ful l e r " phone= " 4 6 7 6 5 7 5 6 5 " / >
<contact f i r s t_name= " Emma " l a s t_name= " Greenman " phone= " 0 2 5 6 6 5 7 4 6 " / >
<contact f i rst_name=" Joshua " last _name = " Harri s on " phone= " 4 7 5 2 8 9 5 6 8 " / >
<contact f i r s t_name="Mad i s on " last_name=" Johnson" phone= " 8 9 1 8 6 3 1 8 7 " / >
<contact f i r s t_name="Matthew " last_name=" Cotman " phone= " l 6 1 8 6 3 1 8 7 " />
<cont act f i r s t name= " Ol ivia " last_name=" Lawson" phone= " 9 4 3 6 5 7 8 7 5 " / >
<contact f i r s t_name= "Andrew" l a s t_name=" Chapman " phone= " 8 7 6 8 67 8 9 6 " / >
<contact f i r s t_name= " Danie l " last_name=" Honeyman" phone= " 9 8 7 65 4 3 8 8 " / >
<contact f i r s t_name= " I sabe l l a " last_name= " Jackson" phone= " 3 1 2 4 3 9 7 8 7 " / >
<contact f i r s t_name= "Wi l l i am" last_name=" Patterson" phone= " 6 8 7 6 9 9 6 9 3 " />
<contact f i r s t_name= " Joseph" las t_name="Godwin " phone= " 9 6 5 4 6 7 5 7 5 " / >
<contact f i r s t name= " Samantha " l a s t name= " Bus h " phone= " 9 0 7 8 6 5 6 4 5 " / >
<contact f i r s t name= " Chri s " last name= " Gateman" phone=" 8 9 6 8 7 4 5 5 6 " / >
< / contac t s >

main .xml
1 6. 1 4.

1 6

< ? xrnl ve r s i on= " l . O " encoding= " ut f- 8 " ?>


<LinearLayout xmlns : andro id= " http : / / scherna s . android . com/ apk/ re s / android"
android : or i entat i on= " ve rt i ca l "
android : layout_width= " fi l l_pa rent "
android : layout_he i ght= " fi l l_pa rent "
< L i s tView
android : id= " @ android : id / l i s t "
android : layout_width= " fi l l_pa ren t "
android : layout_he ight= " fi l l_parent "
android : drawSe lectorOnTop= " fa l s e " / >
< / L inearLayout>

contacts.xml, , :
Xml Pu l l Pa r s e r pars e r

getResources ( ) . getXml ( R . xml . contacts ) ;

getXml ( ) Xml Pu l l Parser,


L- whi l e :
whi le (parse r . getEventType ( ) ! = XmlPu l l Pars e r . END_DOCUENT )
i f ( pa r s e r . getEventType ( )

==

Xml Pu l l Pa r s e r . START_TAG

& & pa r s e r . getName ( ) . equa l s ( " contact " ) )

l i s t . add (parser . getAt t ributeVa lue ( O )


+ parse r . getAttributeValue ( l ) + " \n "
+ pars e r . getAtt ributeVa lue ( 2 ) ) ;
parse r . next ( ) ;


1 6. 1 5 .

pac kage com . sample s . re sxml ;


import j ava . ut i l . Ar rayLi s t ;
import org . xmlpu l l . vl . Xml Pu l l Pa rs e r ;
import android . app . Li s tAct ivi t y ;
import android . os . Bundle ;

ResXmlAct ivity

367

,
import android . widget . ArrayAdapt e r ;
import android . widget . Toas t ;
pu l i c c l a s s ResXmlAct ivi ty extends L i s tAct ivity
@ Ove rride
pul i c void onCreate ( Bundle savedinstance State )
supe r . onCreate ( savedins tance State ) ;
setContentView ( R . layout . ma in ) ;
ArrayL i s t < S t r ing> l i s t

new ArrayL i s t < S t r ing> ( ) ;

try
Xml Pul l Pa r s e r pa r s e r

getRe s ources ( ) . getXml ( R . xml . contacts ) ;

wh i l e . ( pa rs e r . getEventType ( ) !
i f ( parse r . getEventType ( )

Xml Pul l Pa r s e r . END_DOCUENT )


Xml Pu l l Pa r se r . START TAG

& & pa r se r . getName ( ) . equa l s ( " cont act " ) )

l i s t . add ( pa r se r . getAt t ributeVa lue ( O )


+ pa rse r . getAt t ributeVa lue ( l )

" \n "

+ pa rse r . getAt t ributeVa lue ( 2 ) ) ;


parse r . next ( ) ;

cat ch ( Throwale t )

Toas t . ma keText ( thi s ,


" E rror loading L document :

+ t . t o S t r ing ( ) ,

4000)

. show ( ) ;

s e t L i s tAdapte r ( new ArrayAdapt e r < S t r ing> (


thi s , android . R . layout . s imple_l i s t_item 1 , l i s t ) ) ;

, ,
. 1 6.4.

368

1 6

. 1 6.4. L-

1 6 . 5 .
,

.
- , , . .
Android ,
.
.

1 6 . 5 . 1 .
-
,
L- .
, ,
,
. L-:
< ? xrnl ve r s ion= " . 0 " encoding= " u t f- 8 " ?>
<re source s >
<style name= " CustomText " parent= " @ s tyle /Text " >
< item name=" android : text S i z e " > l B sp</ item>

369

,
< item name=" android : textColor " > # 0 0 8 < / i tem>
< / s t yle>
< / re s ources >

, < item>,
. n
,

.
parent < s t yl e > .
, u
. ,
. u,
, , Android.
,
.

TexView:

s t yle.

<TexView
s t yle= " @ style/CustomText "
android : id= " @ + id/ text l "
andro id : layout_width= " f i l l_pa ren t "
android : layout_he ight= "wrap_conten t "
android : text= " He l l o , World ! "

Textview
L-.

Customext,

1 6 .5.2.
- ,

. , ,

,
.
. , ,
L- <s tyle>,
. ,
<appl icat ion>
<act ivity> , . .
.

3 70

1 6

:
< ? xml ve r s i on= " l . O " encoding= " ut f- 8 " ? >
<resources >
< s t y l e narne= " CustomTheme " >
< i t em narne= " andro i d : windowNoT i t l e " >t rue< / i t em>
< i tem narne="windowFrarne " > @ drawale / s creen frarne < / i t em>
< i tem
narne= "windowBac kground " > @ drawa l e / s creen_bac kground_whi te< / i tem>
< i t em narne= "panel ForegroundColor " > # FFO O O O O O < / i tem>
< i tem narne= "panelBackgroundCo lor " > # FFFFFFFF< / i t em>
< i t em narne= "panelTextColor " > ?pane l ForegroundCo lor< / i t em>
< i tem narne = " panelText S i z e " > l 4 < / item>
< i tem narne= "menu i t emTextCo lor " > ?panelTextColor < / i tem>
< i tem narne= "menuitemText S i z e " > ?panelTextS i z e < / i t em>
< / s t yl e >
< / res ource s >

,
AndroidMan ifest.xm l <appl i cat ion>,
andro i d : theme :
android : theme= " @ s t yle / theme_custom"

,
,
<activity> .
, Android
, . ,
Theme . Dia log,
. ' Andro i d :
<activity andro id : theme= " @ android : s t yl e /Theme . Dialog " >

1 6. 5 . 3 .

,
.
D styles.xml res/val ues/.
<resource s > .
D < s t y l e >
, narne= " Cus tomTheme " , -

371

. ,
,
.
<style>
< i t ern> . < i t ern> - .


, . Ecl ipse
New Android Project :

Project name - StylesAndThemes;

Application name - Styles

Package name - . samples . s tyles andtherne s ;

Create Activity - Style sAndThemesAct ivity.

and Therne s ;

res/values/ L-,
- Specia lText - Stars,
styles.xm l . 1 6 . 1 6.

< ?xml ve r s i on= " l . O " encoding= " ut f-8 " ?>
<resources>
<style name= " SpecialTex t " >
< i t em name= " android : text S i z e " > 2 8 sp< / i t em>
< i t em name= " android : t extCol o r " > # FFO O O O < / i tem>
< i t em name= " android : background " > # O O O O O O < / i t em>
< / style>
< s tyle name= " S tars " >
<item name= " android : windowBackground " > @ drawal e / stars < / i tem>
< i t ern name= " andro id : windowNoT i t l e " > t rue < / i t ern>
< / style>
< / resources >

main .xm l TextV i ew,


styles.xml ,
s tyle:
style= " @ style / Spec ialText "

main.xml 1 6. 1 7 .

372

1 6

< ?xrnl ve rs ion= " l . O " encoding= " u t f- 8 " ? >


<Linea rLayout xrnlns : andro id= " http : / / s chemas . android . com/ apk / re s / andro id"
andro id : o r ienta t i on="vert i ca l "
android : layout_width= " f i l l_pa rent "
android : layout_he i ght= " fi l l_pa rent "
android : grav i t y= " center " >
<TextView
s tyle= " @ style / SpecialText "
andro id : layout_he ight= "wrap_content "
androi d : text= " @ s t ri ng / he l lo "
android : gravi t y= " cent e r "
android : layout_width= "wrap_content "
andro id : padding= " Spx " / >
< / L inearLayout >


, android : theme :
android : theme= " @ s t y l e / Stars "

1 6. 1 8 .

< ?xml ver s i on= " l . O " encoding= " ut f - 8 " ? >
<mani fest xmlns : andro id= " http : / / s chemas . android . com/apk/ res /android"
package= " com . s amples . stylesandtheme s "
android : vers ionCode= " l "
android : ve r s i onName= " l . O " >
<app l i ca t i on
andro i d : i con= " @ drawa l e / i con"
andro i d : label= " @ s t ring/app_name "
andro i d : theme= " @ style / Stars " >
<activity
android : name= " . StylesAndThemesActivity"
andro id : labe l= " @ s t r i ng /app_name " >
< intent - f i l t e r>
<action android : name= " andro id . intent . act ion . AIN " / >
<category andro id : name= " android . intent . category . LAUNCHER" / >
< / intent - fi lter>

373

< /activity>
< / appl i cation>
<use s - sdk android : minSdkVe rsion= " "
< /man i fe s t >


. 1 6. 5 .

. 16.5.

1 6 . 6 .
- ,
assets/. res/
. ,
assets/ R.
.
- , assets/.
As s etManager. ,
res/,
.
: ,
,
Android.
, -

1 6

374

. , assets/
.
,
, Create New
Project :

Proj ect name - Res Font sApp;

Application name -

Package name - . samples . font s ;

Create Activity -

Load font s from a s s e t s sample;

FontsActivity.

mai .xml LinearLayout


extView,
.
L- main.xm l
1 6. 1 9 .

< ? xml ve rs ion= " . 0 " encoding= " ut f - 8 " ? >


<LinearLayout
xmlns : andro id= " http : / / s chemas . andro i d . com/apk/res / andro id"
android : id= " @ + id/ LinearLayout O l "
android : layout_width= " fi l l_parent "
andro id : layout_height= " fi l l_parent "
android : or i entation= " ve rt i ca l "
android : gravity= " cente r " >
<TextView
android : text= " Libe rtine I t a l i c "
androi d : id= " @ +id/text l "
android : layout_width= " wrap_content "
android : layout_he ight= "wrap_content "
androi d : textS i z e= " sp"
android : padding= " l O sp " />
<TextView
android : text= "Aaddon font "
android : id= " @ +id/text2 "
android : layout_width= " wrap_content "
android : layout_he i ght= "wrap_content "
android : textS i z e= " s p "
android : padding= " l O sp " / >

3 75

,
<TextView
android : text= " a font "
android : id= " @ + id/text "
android : layout_width= "wrap_content "
androi d : layout_he ight="wrap_content "
android : text S i ze= " s p "
android : padding= " l O sp " / >
<TextVi ew
android : text= "A Yummy Apo logy"
android : id= " @ + id/text 4 "
android : layout_width= " wrap_content "
android : layout_he ight= "wrap_content "
android : textS i ze= " sp"
android : padding= " l O sp " / >
< / LinearLayout >

:
Linu- Libertine ,
http://www . urbanfonts.com/free-fonts.htm .
extVi ew,
Typeface,

Typeface . createFromAs set ( ) . create FromAs set ( )


:

As s etManager, getAs sets ( ) ;

, .
:

extView

TextView text

( TextView ) f indViewByid ( R . id . text_i ) ;

Typeface face

Typeface . c reateFromAs s e t (

getAs s e t s ( ) , " font s / l ibe rtine_i t . t t f " ) ;


text . setTypeface ( face ) ;

FontsActi vi ty

pac kage com . sample s . fonts ;


import andro id . app . Activi t y ;
import android . graphi c s . Type face ;
import android . os . Bundle ;
import android . widget . TextView ;

1 6 .20.

1 6

3 76
pu l i c c l a s s FontsActivity extends Act ivity
@ Ove rride
pu l i c void onC reate ( Bundl e s avedins tanceState )
supe r . onCreate ( savedinstanceState ) ;
setContentView ( R . layout . main ) ;
/ 1
( TextView ) f indViewByid ( R . i d . text l ) ;

final TextView text l

text l . s e tTypeface ( T ypeface . c reateFromAsset (


getAs s e t s ( ) , " font s / l ibe rt ine_it . t t f " ) ) ;
final TextView text 2

( TextView ) findViewByid ( R . i d . text 2 ) ;

text2 . s etType face ( T ypeface . c reateFromAsset (


getAs sets ( ) , " font s /abaddon . t t f " ) ) ;
final TextView text

( T extView ) findViewByid ( R . id . text ) ;

text . s etType face ( T ype face . c reateFromAsset (


getAs s e t s ( ) ,
f ina l TextView text 4

" font s /apapa . tt f " ) ) ;

( TextView ) findViewByid ( R . i d . text 4 ) ;

text 4 . s etType face ( T ype face . createFromAsset (


getAs s e t s ( ) , " fonts /ayummy apology . t t f " ) ) ;

. 1 6.6. , assets/

377

, ,
. 1 6.6.

1 6 . 7 .
Android
. ,
, , ,
, ,
.
Android
,
.
,
, ,
.

1 6 . 7 . 1 . ,
, (
), ,
Android
res/values/strings.xm l .
,
.
, ,
res/values/strings.xm l
. ,
: ,
, , - ,
, . .

. ,
. ,
.
,
- -
, ,
.

1 6

3 78

1 6 . 7 . 2 .
,
,
. . 1 6. 1 .

1 6. 1 .

stri n g s .x m l

Defa u l t

E n g l i s h 1 U n ited Kingdom

r e s /va lues /

ru-rRU

Russian 1 R u ssia

res /va lues- ru /

de-rDE

German 1 Ge rmany

res /values-de /

j a-rJ P

J apa nese 1 J apan

res /value s - j a /

fr-rFR

French 1 France

r e s /va l ue s - f r/

fr-rCA

French 1 Canada

res /value s - fr /

e n-rCA

E n g l i s h 1 Canada

res /values /

en-rUS

English 1 U n ited States

res /va lues /

,
,
res/val ues-en/.
,

. res/
.
res/ values-ru/ -
.
, . 1 6.7.
,
, , ,
1 6 .2 1 . res/values-ru/.
i3

res

ii! i1:7 dr w
iiJ GiJ, l ayout
i3 i1:7 values

l.i!J strings . xml


i3 tz,. va lues-ru
l.i!J strings . xml
. 1 6.7.

, u

3 79

< ? xml ve r s i on= " . 0 " encoding= " ut f- 8 " ? >


<resources>
< s t r ing nm = " _nm " > ax < / s t r ing>
< s t r ing name="btn_o k " >Coxpa < / s t ring>
< s t r ing name="btn_cance l " >Oea < / s t ring>
< s t r ing name= " f i e l d_name " > : < / s t ring>
< s t ring name= " f ield_phone " >Te . : < / s t ring>
< s t r ing name= " t i t l e_add " >o oa < / s t r ing>
< s t r ing name= " t i t l e_edi t " >e oa < / s t r ing>
< s t ring name= " t it l e_de l ete " >Ya oa ? < / s t r ing>
< s t r ing name="menu_add " >oa < / s t ring>
< s t ring name="menu_edi t " >e < / s t ring>
< s t r ing name="menu_de lete " >Ya < / s t r ing>
< s tring name= " toast_no t i f y " > epe oa ! < / s t ring>
< / resources>

, .
,
.
. Application Launcher
Settings 1 Language & keyboard 1 Select locale 1
, . \ 6 . 8 .

. 1 6.8.

1 6

380

Application Launcher.
Application Launcher r .
. .
,
, . 1 6 .9.

. 1 6. 9 . n

17

ndrid-
. Drawale
.

:
D View ;
D .

view ,
,
,
.

1 7 . 1 . Drawa/e
Android
- andro id . graphics . drawale.
Drawale
. . D rawale
, BitmapDrawale, ShapeDrawale,
PictureDrawale, Layerorawale . Android
. 1 7 . 1 .

Drawale:

D , res/drawale/;
D L-,
Drawale.

1 7

382

Object

Drawae

BitmapDrawae
Clip Drawae
ColorDrawae
DrawaeContainer

1
1
1
1

An imationDrawae
LeveiListDrawae
State ListDrawae

G radientDrawae
lnsetDrawae
LayerDrawae

N inePathDrawae
PictureDrawae
RotateDrawae
ScaleDrawae
Shape Drawae

1
1
1

1
1
1
1
1
1

TransitionDrawa e

PaintDrawae

. 1 7. 1 .

-
. :
D PNG - ;
D J PEG - ;
D GIF - .

,
.

.
, res/drawaie/
,
aapt. ,
. -

383

(* .bmp, aapt
) , res/raw/,
aapt.
-
.

1 7 2 Drawa/e

.


Drawale. , Drawale,
:
Re sources res

mContext . getResources ( ) ;

Drawale myimage

res . getDrawale ( R . drawale . my_image ) ;


,
. ,
orawale ,
, alpha ( ),
Drawale, .

. , ,
XML. Drawa e,

,
, Drawale XML - .
, Drawae
,
Drawale XML,
.
Drawale L-,
res/drawae/ .
, Resource s . getDrawae ( )
L-. ,
Drawa e, inflate ( ) ,
XML .

Drawa e .

1 7

384

1 7 .2. 1 . TransitionDrawa/e
Drawale -
.
Trans i tionDrawale .
Ecl ipse New Android Proj ect:
Proj ect name - Trans i t ion;
Application name - Trans i tiori Sample;
Package name -

samples . trans i tion;

C reate Activity - TransitionActivity.

ImageView,
1 7 . 1 .

<?xml version= " l . O " encoding="utf-8 " ?>


<LinearLayout xmlns : android="http : / / schemas . android . com/apk/ res/android"
android : orientation="vertical "
android : layout_width= " fil l_parent "
android : layout_height=" fi l l_parent "
android : gravity=" cente r " >
<ImageView
android : id=" @ +id/ image "
android : layout_width= " wrap_content "
android : layout_height="wrap_content "
android : src= " @drawale /photol " />
</LinearLayout>

res/drawaie/ , photo J .j pg
photo2.j pg. -,
Resources/, Adroid SDK - ,
, adroid-sdk-widows/platforms/adroid2/samples/ApiDemos/res/drawae/.
res/drawaie/ tra sitio .xm l ,
. transition.xml
1 7 .2.

385

< ? xml ve rs ion= " l . O " encoding= " ut f- 8 " ? >


<t rans i t i on xmlns : android= " http : / / s chemas . android . com/ap k / re s / andro id " >
< i tem andro i d : drawale= " @drawale /photo l " ></ i t em>
< i t em android : drawale= " @ drawale /photo2 " > </ i t em>
< / t rans i t i on>

LoadimageActivity T rans i t i onDrawale


ImageView:
Resources res
mTrans i t ion

thi s . getRe s ources ( ) ;


( T rans i t i onDrawal e ) res . getDrawale ( R . drawal e . t rans i t i on ) ;

LoadimageAc t i vi ty onC l i c k ( ) ,

1 :
t rans i t ion . s ta rtTrans i t ion ( l O O O ) ;

LoadimageAct ivity

1 7 .3 .

package com . sample s . loadimage ;


import android . app . Ac t ivi t y ;
import android . content . re s . Re s ource s ;
import android . graphi cs . drawale . Trans i t ionDrawale ;
import andro id . os . Bundle ;
import android . vi ew . View;
import andro id . view . Vi ew . OnCl ickLis tene r ;
import android . widget . ImageView;
pu l i c class T rans i t i onAct ivity extends Act ivity
implements OnCl ickLis tene r
pr ivate ImageVi ew image ;
p rivate Trans i t ionDrawale mT rans i t i on ;
@Ove rride
pu l i c void onCreate ( Bundle savedinstanceState )
supe r . onCreate ( savedinstanceState ) ;
setContentView ( R . layout . ma in ) ;
image

( ImageView ) findVi ewByid ( R . id . image ) ;

image . s etOnC l i c kL i s tener ( thi s ) ;

1 7

386
Resources res
mTrans i t i on

this . getRe s ources ( ) ;


( T rans i t i onDrawal e ) res . get D rawal e (

R . drawae . t rans i t i on ) ;

1 1 n
11 1
@ Ove r ride
pu l i c void onC l i c k (View v )

image . s e t image Drawale (mTrans i t i on ) ;


mT rans i t i on . s tartT rans i t i on ( l O O O ) ;

. (
)
(. 1 7 .2).

. 1 7.2.

1 7 2 2 ShapeDrawa/e
.

,
ShapeDrawale .
ShapeDrawae
.

387

Android
, Shape :
PathShape;
RectShape ;
Arc Shape ;
Ova l Shape;
RoundRectShape.

. 1 7 .3 .
Object

-----,

L___--1

Shape

1
1

_,,_

,--------,

RectShape

PathShape

1
1
1

--------,

ArcShape

OvaiShape
Round RectShape

. 1 7.3.

Shape Drawale - Drawale,


, orawale.
ShapeDrawale Rect Shape,
. . h . Shapeorawale
. ,
. ,
- .
Rect Shape
. ( )
1 -2 , :
Shape Drawale d

new Shape Drawale ( new RectShape ( ) ) ;

d . set intr ins icHeight ( 2 ) ;


d . s et i nt rins icW i dth ( l 5 0 ) ;
d . getPaint ( ) . s etColor ( Color . AGENTA) ;

ova l Shape ( ):
Shape Drawale d

new Shape Drawal e ( new Ova lShape ( ) ) ;

d . s e t i nt r in s i cHeight ( l O O ) ;
d . set int r insicW idth ( l 5 0 ) ;
d . get Paint ( ) . s etColor ( Colo r . RE D ) ;

1 7

388

( Round.Rect )
. Round.Rect
:
Round.Rect Shape ( float [ ] oute rRadi i , Rect F inset , float [ ] inne rRadi i )

RoundRect Shape :
D


. ,
.
, nul l ;

Rect F,
.
Rect F :
.
, nul l;

innerRadi i -
. -
,
. ,
nul l .

oute rRadi i -

inset -

,
:
float [ ] outR

new float [ ]

rectF

RectF

float [ ] inR

, , , , , , ,

new RectF ( 8 , 8 , 8 , 8 ) ;
new float [ ]

Shape Drawale d

{ , , , ,

new ShapeDrawal e (

new Round.RectShape ( outR, rectF, inR ) ) ;


d . set intr ins icHe ight ( l O O ) ;
d . set intrins icWidth ( l 5 0 ) ;
d . getPaint ( ) . s etColor ( Color . WHITE ) ;

Path ,
,
. ( )
moveTo ( ) l ineTo ( ) . , Path
:
Path

new Path ( ) ;

p . moveTo ( 5 0 , 0 ) ;
p . l ineTo ( 2 5 , 1 0 0 ) ;

389


p . l ineTo ( l 0 0 , 5 0 ) ;
p . l ineTo ( 0 , 5 0 ) ;
p . l ineTo ( 7 5 , 1 0 0 ) ;
p . l ineTo ( 5 0 , 0 ) ;
ShapeDrawale d = new ShapeDrawale ( new PathShape ( p , 1 0 0 , 1 0 0 ) ) ;
d . set int r i n s i cHe i ght ( 1 0 0 ) ;
d . s e t int rinsicW idth ( 1 0 0 ) ;
d . getPaint ( ) . setColor ( Colo r . YELLOW ) ;
d . getPaint ( ) . s e t S t yle ( Paint . Style . STROE ) ;

ArcShape .
:
ArcShape ( float sta rtAngl e ,

float sweepAngle )

- ,
- .
ShapeDrawal e, Drawale,
android . graph i c s . drawale,
, s etAlpha ( ) -
, setColorFil ter ( ) . .
ShapeDrawale Shape
, IrnageView
. Ecl ipse
New Android Project:
D Project name -

ShapeDrawale;

D Application name - ShapeDrawal e

S ample;

D Package name - . sarnples . shapedrawale;


D C reate Activity - ShapeDrawal eAc t ivity.

1 7 .4.

IrnageView,

< ?xrnl ve rs ion= " 1 . 0 " encoding= " utf-8 " ?>
<LinearLayout xrnlns : andro id= " http : / / s cherna s . andro id . com/apk / r e s / andro i d "
android : id= " @ + id/ root "
andro id : layout_width= " fi l l_pa rent "
andro id : l ayout_he i ght= " fi l l_parent "
android : or i entation= " ho r i z ontal "
android : layout_gravit y= " center_ve r t i ca l l cente r_ho r i z ontal " >

1 7

390
< IrnageView
android : id= " @ + id/ image "
android : layout_width= "wrap_content "
android : layout_he ight = " wrap_content "
android : minHe i ght= " 9 0px "
android : minWidth= " 9 0px "
android : layout_rnargin= " l l 5px " / >
< /L inearLayout >

DrawCanvasActivity

1 . Line - .
2 . Oval - .
3. Rectangle - .
4 . RoundRect. Fill - .
5 . Path - .
6. Arc - .
Imagevi ew
.
onC reateOpt i onsMenu ( )
. DrawCanvasActivity
1 7. 5 .

pac kage com . s ample s . shapedrawale ;


import android . app . Activi t y ;
import android . g raphi c s . Color ;
import android . graphi c s . Pa int ;
irnport android . g raphics . Path;
import andro id . graphi cs . Re c t F ;
import android . graphi cs . drawale . ShapeDrawale ;
import android . g raphi cs . drawale . shape s . ArcShape ;
import android . g raphi c s . drawale . shape s . Ova lShape ;
import android . graphi cs . drawale . shape s . PathShape ;
import android . g raphi c s . drawae . shape s . RectShape ;
import android . graphi c s . drawale . shapes . RoundRect Shape ;
import android . os . Bundle ;

391


import android . view . Menu ;
import android . vi ew . Menui tem;
import android . widget . ImageView;
pu l i c c 1 a s s Shape DrawaleActivity extends Act ivi ty
11
pr ivate s t a t i c fina1 int I DM LINE

101 ;

p r ivate s t a t i c fina1 int I DM OVAL

102 ;

private s t a t i c fina1 int I DM RECT

103 ;

p r ivate s t a t i c fina1 int I DM ROUNDRECT


private s t a t i c fina1 int I DM STAR
pr ivate s t a t i c fina1 int I DM ARC

104 ;

105;
106;

private ImageView mimage ;


@ Ove rr ide
protected void onCreate ( Bund1e s avedinstanceState )
super . onCreate ( s avedins tanceState ) ;
setContentView ( R . 1 ayout . ma in ) ;
mimage

( ImageView ) findViewByid ( R . id . image ) ;

@ Ove r ri de
pu i c boo1ean onC reateOpt ionsMenu ( Menu menu )
menu . add (Menu . NONE , I DM_LINE , Menu . NONE ,

" Line " ) ;

menu . add ( Menu . NONE , I DM_OVAL , Menu . NONE ,

" Ova1 " ) ;

menu . add ( Menu . NONE , I DM_RECT , Menu . NONE ,

" Rectang1e " ) ;

menu . add ( Menu . NONE , I DM_ROUNDRECT , Menu . NONE , " Round Rect . Fi 1 1 " ) ;
menu . add ( Menu . NONE , I DM_STAR , Menu . NONE , " Path" ) ;
menu . add ( Menu . NONE , I DM_ARC , Menu . NONE , "Arc " ) ;
return ( supe r . onCreateOpt ionsMenu (menu ) ) ;

@ Ove rride
pul i c boo 1ean onOptions i t emSe1ected ( Menu i tem i tem)
ShapeDrawae d

nu1 1 ;

swi t ch ( i tem . get i t emid ( ) )


case I DM LINE :
d

new Shape Drawale ( new RectShape ( ) ) ;

d . set int r i n s i cHe i ght ( 2 ) ;

392

1 7
d . set intrins i cWidth ( 1 5 0 ) ;
d . get Paint ( ) . s etCo 1 o r ( Co1or . AGENTA ) ;
bre a k ;
cas e I DM OVAL :
d

new ShapeDrawale ( new Ova 1 Shape ( ) ) ;

d . set i nt r i n s i cHe i ght ( 1 0 0 ) ;


d . set intrins i cWidth ( 1 5 0 ) ;
d . get Paint ( ) . s etCo1or ( Co1or . RE D ) ;
break ;
case I DM RECT :
d

new ShapeDrawale ( new Rect Shape ( ) ) ;

d . set intrinsicHe i ght ( 1 0 0 ) ;


d . set int r i n s i cWidth ( 1 5 0 ) ;
d . get Paint ( ) . s etCo1or ( Co1or . BLUE ) ;
bre a k ;
case I DM ROUNDRECT :
f1oat [ ] outR
Re ctF

float [ ] inR
d

, , , , ,
new Rect F ( 8 , 8 , 8 , 8 ) ;

new f1oat [ ]

rectF

new float [ ]

, ,

, , , , , , ,

new ShapeDrawa1e ( new RoundRectShape ( outR, rectF, inR) ) ;

d . set i ntrinsicHe i ght ( 1 0 0 ) ;


d . set i nt r i n s i cWidth ( 1 5 0 ) ;
d . get Paint ( ) . s etCo1or ( Co1or. . WITE ) ;
brea k ;
case I DM STAR :
Path

new Path ( ) ;

p . moveTo ( 5 0 , 0 ) ;
p . 1 ineTo ( 2 5 , 1 0 0 ) ;
p . 1 ineTo ( 1 0 0 , 5 0 ) ;
p . 1 ineTo ( 0 , 5 0 ) ;
p . 1 ineTo ( 7 5 , 1 0 0 ) ;
p . 1 ineTo ( 5 0 , 0 ) ;
d

new ShapeDrawale ( new PathShape ( p , 1 0 0 , 1 0 0 ) ) ;

d . set int r i n s i cHe ight ( 1 0 0 ) ;


d . set int rinsicWidth ( 1 0 0 ) ;
d . get Paint ( ) . setCo1or ( Co1or . YELLOW ) ;
d . get Paint ( ) . s e t S ty1e ( Pa int . Sty1e . STROE ) ;
bre a k ;
c a s e I DM ARC :
d

new ShapeDrawale ( new ArcShape ( O , 2 5 5 ) ) ;

d . set int r i n s i cHe i ght ( 1 0 0 ) ;

393


d . s et i ntrins i cWidth ( l O O ) ;
d . getPaint ( ) . s etColor ( Colo r . YELLOW ) ;
bre a k ;
mimage . s etBac kgroundD rawal e ( d ) ;
return t rue ;

.
ImageView
(. 1 7 .4).

. 1 7.4.

1 7 3
.

,
. ,
.
- .
:
D , ,
Vi ew,

1 7

394
inva l i date ( )

onDraw ( ) ;

Surfaceview.

canvas ,
, drawBi tmap ( ) , drawRect ( ) , drawext ( )
. , ,
draw ( ) . , Drawae
. Drawae draw ( ) ,
canvas .
,
.
View . onDraw ( ) , Canva s .
Canvas Sur faceHolder .
loc kCanvas ( ) , SurfaceView.
Android onDraw ( ) .
, ,
inval idate ( )
, Android onDraw ( )
.

ShapeDrawae draw ( ) ,
View, Shape Drawa e
View . onDraw ( ) :
,

c l a s s CustomView extends View


private ShapeDrawae mDrawale ;

@ Ove rride
protected void onDraw ( Canvas canvas )
1 1
mDrawae
new Shape Drawale ( new Rect Shape ( ) ) ;
mDrawae . s e t intrins i cHe i ght ( 2 ) ;
mDrawale . s et intrins i cWidth ( l 5 0 ) ;
mDrawa le . get Paint ( ) . s etColor ( Color . AGENTA) ;

/1

mDrawae . draw ( canvas ) ;

,
Imageview, , -

395

. Ecl ipse
New Android Project:

Proj ect name - Canvas ;

Application name - Draw

Package name - . sarnples .

Create Activity - DrawCanvasAct ivity.

o n Canvas Sarnple;
canvas ;

DrawCanvasActivity
DrawCanvasView, View,
.
DrawCanvasView
.
ShapeDrawale
DrawCanvasView .
DrawCanvasActivity 1 7 .6.

package com . sarnples . canvas ;


import android . app . Activi t y ;
import android . graphi c s . Color ;
import android . graphi c s . Paint ;
import android . graphics . Path;
import android . g raphi c s . Rec t F ;
import android . graphi c s . drawae . Shape Drawae ;
import android . graphi c s . drawae . shape s . ArcShape ;
import android . g raphi cs . drawale . shape s . Ova lShape ;
import andro id . g raphi cs . drawale . shapes . PathShape ;
import android . g raphi cs . drawale . shape s . RectShape ;
import android . g raphi cs . drawa le . shape s . RoundRectShape ;
import android . os . Bundle ;
import android . view . Menu ;
import android . view . Menu i t em;
pu l i c c l a s s Shape DrawaleActivity extends Act ivi t y

1 1
pu l i c s t at i c f inal int I DM LINE

101 ;

pu i c s t a t i c f inal int I DM OVAL

102 ;

pu l i c s t a t i c f inal int I DM RECT

103 ;

pu l i c stat i c final int I DM ROUNDRECT

104 ;

396

1 7
pu i c static fina1 int I DM STAR
pu l i c s t a t i c fina1 int I DM ARC

105 ;
106;

private DrawCanvasView rnView ;


@ Ove r r ide
protected void onCreate ( Bund1e savedinstanceS t ate )
supe r . onC reate ( s avedinstanceS t ate ) ;

11
11

n - ,

rnView

new DrawCanva sView ( th i s ) ;

setContentView (rnView ) ;

@ Ove r ride
pu 1 i c boo1ean onCreateOpt ionsMenu ( Menu rnenu )
rnenu . add (Menu . NONE , r o_LINE , Menu . NONE , " Line " ) ;
rnenu . add ( Menu . NONE , I DM_OVAL , Menu . NONE , " Ova 1 " ) ;
rnenu . add ( Menu . NONE , I DM_RECT , Menu . NONE , "Rectang1e " ) ;
Fi l l " ) ;

rnenu . add ( Menu . NONE , I DM_ROUNDRECT , Menu . NONE ,

" Round Rect .

rnenu . add ( Menu . NONE , I DM_STAR , Menu . NONE , " Path" ) ;


rnenu . add ( Menu . NONE , I DM_ARC , Menu . NONE , "Ar c " ) ;
return ( supe r . onCreateOpt i onsMenu (rnenu ) ) ;

@ Ove r ride
pu 1 i c boo 1ean onOptions iternSe1ected ( Menuitern i tern)
Shape Drawae d

new Shape Drawale ( ) ;

switch ( itern . geti ternid ( ) )

case I DM L INE :
d

new Shape Drawal e ( new RectShape ( ) ) ;

d . s etintrins i cHe ight ( 2 ) ;


d . s e t intrins i cWidth ( l 5 0 ) ;
d . getPa int ( ) . s etCo1or ( Co1or . AGENTA) ;
brea k ;
case I DM OVAL :
d

new Shape Drawale ( new Ova 1Shape ( ) ) ;

d . s e t i nt r i n s i cHeight ( l O O ) ;
d . s e t i nt rins i cWidth ( l 5 0 ) ;
d . getPaint ( ) . s etCo1o r ( Co1or . RE D ) ;
bre a k ;

397

case I DM RECT :
d

new Shape Drawale ( new RectShape ( ) ) ;

d . s etintrinsicHei ght ( 1 0 0 ) ;
d . s et i n t r ins i cWidth ( 1 5 0 ) ;
d . getPa int ( ) . s etColor ( Color . BLUE ) ;
bre a k ;
c a s e I DM ROUNDRECT :
float [ ] outR
Rec t F

float [ ) inR
d

new float [ ]

6, 6, 6, 6, 6, 6, 6, 6

new Rect F ( 8 , 8 , 8 , 8 ) ;

rectF

new float [ ]

{ 6,

6, 6, 6, 6, 6, 6, 6

new Shape Drawale ( new RoundRectShape ( outR, rect F

d . s e t intrins i cHe ight ( 1 0 0 ) ;


d . set int r in s i cWidth ( 1 5 0 ) ;
d . getPa int ( ) . s etColor ( Color . WHITE ) ;
bre a k ;
c a s e I DM STAR :
Path

new Path ( ) ;

p . moveTo ( 5 0 , 0 ) ;
p . l ineTo ( 2 5 , 1 0 0 ) ;
p . l ineTo ( 1 0 0 , 5 0 ) ;
p . l ineTo ( 0 , 50 ) ;
p . l ineTo ( 7 5 , 1 0 0 ) ;
p . l ineTo ( 5 0 , 0 ) ;
d

new ShapeDrawale ( new PathShape ( p , 1 0 0 , 1 0 0 ) ) ;

d . s e t intrinsicHeight ( 1 0 0 ) ;
d . set int r ins i cWidth ( 1 0 0 ) ;
d . getPaint ( ) . s etColor ( Color . YELLOW ) ;
d . getPaint ( ) . s e t S t yle ( Pa int . Style . STROE ) ;
bre a k ;
c a s e I DM ARC :
d

new ShapeDrawale ( new ArcShape ( O , 2 5 5 ) ) ;

d . s et i n t r ins i cHei ght ( 1 0 0 ) ;


d . s e t intrins i cWidth ( 1 0 0 ) ;
d . getPa int ( ) . s etColor ( Color . YELLOW ) ;
bre a k ;
}

11

Shape Drawale

mView . s etDrawale ( d ) ;
return t rue ;

inR ) ) ;

398

1 7

DrawCanvasView setDrawale ( ShapeDrawale )


ShapeDrawale,
. inva l i date ( ) ,
. Adroid
onDraw ( ) ,
.
onDraw ( ) view
canvas, .
onDraw ( ) , Android
canvas , .

D rawCanvasView

J-! 1 7 . 7 .

pac kage com . sample s . canvas ;


import android . content . Context ;
import android . graphics . Canvas ;
import android . graphi c s . drawale . Shape Drawale ;
import android . view . View;
class DrawCanvasView extends View

11

private s t a t i c final int START

10;

private s t a t i c final int START

10 ;

private ShapeDrawale mDrawale ;


pu l i c DrawCanvasView ( Context contex t )
super ( context ) ;
s e t Focusale ( t rue ) ;
mDrawa le

11

new Shape Drawale ( ) ;

, Shape Drawale

pu l i c void s e t Drawale ( Shape Drawale shape )


mDrawale

11

shape ;

ShapeDrawale

mDrawale . s etBounds ( START_X , START_Y ,


START + mDrawale . getintrins i cWidth ( ) ,
START + mDrawale . ge t intrins icHei ght ( )

) ;

399



inval idate ( ) ;

11

@ Ove r r i de
protected vo id onDraw ( Canvas canva s )
mDrawal e . draw ( canvas ) ;

.
.

(. 1 7 .5).

Rau11d Rct.

Pth

Arr

. 1 7.5.

18

ndrid-
Android SDK,

android . view . animationpackages .
Android :
LJ Tween Animation - ;
LJ Frame Animation - .

1 8 . 1 .
-
, , View. ,
, extView , ,
. TextView ,
. android . view .
animationpa c kages ,
. . 1 8 . 1 .
:
LJ Animat ionset - , ,

. Animat ionSet -
, , ;
LJ AlphaAnimation - ,

;
LJ RotateAnimat ion - ,

402

1 8

LJ ScaleAnima t i on - ,

;
LJ T rans lateAnimat ion - ,

.
Object

------,

Ani mation

Ani mationSet
AlphaAnimation
RotateAni mation
ScaleAnimation
TranslateAnimation

1
1
1
1
1

. 1 8. 1 . Android

,
.
. ,
( ,
,
. .), (,
).
, .
,
.
L-
. L
( L-),
,
.

1 8. 1 . 1 . L-
L- res/an im/ .
:
<a lpha>, <scale>, <t rans late>, <rotate> < s e t >,
(
<set> ). L-
. 1 8 .2.

403

<set>

<set>

1
<scale>

<set>

<translate>

<scale>
<translate>
<alpha>

<alpha>
<scale>
<translate>
<rotate>

1
1
1

1
1
1
1
1

. 1 8. 2 . L-

.
, s t a rtOffset
, :
andro id : s tartOffset= " O O O "


. .


<a lpha>, <scale>, < t rans late>, <rotate> <set>
, Animation:
Ll durat ion - ;
Ll s t a rtOffset - ,

;
Ll f i l lBe fore - t rue,

;
Ll f i l lAfter - t rue,

;
Ll repeatCount - ;
Ll repeatMode - .

:
;

1 8

404

LJ zAdj ustment - Z ,

(, );
LJ interpolator - ,

,
, .
,
R . s t yl ea le, :
android : int e rpolator= " @ android : anim/dece lerate_interpo lator"

<set>
< s e t > - , .
Animat ionset. shareinterpolator,

.

<alpha>
.
:

AlphaAnima t i on.

LJ fromAlpha - ;
LJ toAlpha - .

1 ,
.

<sca/e>
< s ca l e >
ScaleAnima t i on.
( ),
. < s c a l e >
:
LJ fromXSca le - ;
LJ toXScale - ;
LJ fromYS ca le - ;
LJ toYScale - ;
LJ pivotx - - ;
LJ pivotY - - .

405

<translate>
<t ran s late> -
. rans lateAnima t i on
:
LJ fromXDe l t a - ;
LJ toXDel ta - ;
LJ fromYDe l t a - ;
LJ toYDe l t a -

:
1 . .
2. - 1 00% 1 00% .
3 . - 1 % 1 %,
.

<rotate>

<rotate>

Rotat eAnimation.

LJ fromDegree s - ;
LJ toDegrees - ;
LJ pi votx - ;
LJ pi votY - .

1 8. 1 . 2 .
,
.
- ,
, . Ecl ipse
New Android Project:
LJ Proj ect name - TweenAnimat ionShape s ;
LJ Application name - Tween Anima t i on Sample;
LJ Package name - com . s ample s . tweenanimat ionshape s ;
LJ Create Activity - TweenAnimat ionActivity.

res/anim/ L- :
alpha.xml, rotate.xml, scale.xml, translate.xml, -

406

1 8

, total .xml,
<alpha>, <scale>, <t rans late>,
<rotate> .
alpha.xml, rotate.xml, scale.xml, translate.xml total .xm l
1 8 . 1 - 1 8 . 5 .

< ? xml ve rs ion= " l . O " encoding= " ut f- 8 "


<set xmlns : android= "http : / / s chema s . andro id . com/ap k / re s / android"
android : shareinterpol ator= " fa l s e " >
<a lpha
android : frornAlpha= " O . O "
android : toAlpha= " l . O "
android : s tartOffset= " O "
androi d : durat i on= " 5 0 0 0 " / >
< / set>

< ?xrnl ve r s i on= " . 0 " encoding= "utf- 8 "


<set
xrnlns : android= "http : / / s chernas . android . com/apk/ res / android"
android : share i nterpol ator= " fa l s e " >
< rotate
android : fromDegree s = " O "
android : toDegrees=" 3 6 0 "
android : pivotX= " 5 0 % "
android : pivotY= " 5 0 % "
android : durat ion= " 5 0 0 0 "
< / set>

< ? xml ve rs ion= " . 0 " encoding= " u t f- 8 "


<set
xrnlns : andro id= " http : / / s chernas . android . com/ apk / res / andro id"
android : share i nterpola tor= " fa l s e " >
<scale
android : pivotX= " S O % "


android : pivotY= " S O % "
android : fromXS cale= " l . O "
android : fromYScale= " l . O "
android : toXScale= " 2 . 0 "
android : toYScale= " 2 . 0 "
android : dura t i on= " 2 5 0 0 "
<scale
android : st a rt0ffset= " 2 50 0 "
android : durat i on= " 2 5 0 0 "
android : pivotX= " S O % "
android : pivotY= " S O % "
android : fromXS cale= " l . O "
android : fromYScale= " l . O "
androi d : toXScale= " O . S "
android : toYScale= " O . S "
</set>

< ?xml ve r s i on= " l . O " encoding= " ut f- 8 "


<set xmlns : android= "http : / / s chema s . android . com/ap k / re s /android"
android : sha reinte rpol ator= " fa l s e " >
< t ranslate
android : toYDe lta= " - 1 0 0 "
android : f i l lAfter= " t rue "
android : durat i on= " 2 5 0 0 " / >
< t ranslate
android : toYDe lta= " l O O "
android : fi l lAfter= " t rue "
android : durat i on= " 2 5 0 0 "
android : s ta rt0ffset= " 2 5 0 0 " / >
< / s et>

< ? xml ve r s i on= " l . O " encoding= "utf- 8 "


<set xrnlns : andro id= "http : / / schemas . android . com/ap k / re s /android"
android : shareinterpolator= " fa l s e " >
<a lpha
android : fromAlpha= " O . O "

407

18

408
android : toAlpha= " l . O "
android : st a rtOffset= " O "
android : durat i on= " S O O O " / >
<scale
android : durat i on= " 2 5 0 0 "
android : pivotX= " S O % "
android : pivotY= " S O % "
android : fromXSca l e= " l . O "
android : fromYScale= " l . O "
android : toXScale= " 2 . 0 "
android : toYScale= " 2 . 0 "
< rotate
android : fromDegrees=" O "
android : toDegrees= " 3 6 0 "
android : pivotX= " S O % "
androi d : pivotY= " 5 0 % "
android : durat i on= " S O O O "
<translate
android : toYDe l t a= " - 1 0 0 "
android : fi l lAfter= " fa l s e "
android : dura t i on= " 2 5 0 0 "
<scale
android : durat i on= " 2 5 0 0 "
android : st a rt0ffset=" 2 5 0 0 "
android : p ivotX= " S O % "
android : pivotY= " S O % "
android : fromXS cale= " l . O "
android : fromYScale= " l . O "
android : toXS cale= " O . S "
android : toYScale= " O . S "
< t ranslate
android : toYDe l t a= " l O O "
android : fi l lAfter= " fa l s e "
android : durat ion= " 2 5 0 0 "
android : start0ffset=" 2 5 0 0 "
< / set>

, ,
L-, shape.xml
res/drawae/. ShapeDrawale
. shape.xm l
1 8.6.

409

< ?xml ve r s i on= " l . O " encoding= " ut f- 8 " ? >


<shape
xmlns : android= " http : / / s chemas . android . com/apk / r e s / android"
android : shape= " rectangl e " >
< s o l i d android : color= " # FO O " / >
< / shape>


ImageView, 1 8 .7.

< ? xml ve r s i on= " l . O " encoding= " ut f- 8 " ? >


<Linea rLayout
xmlns : androi d= " ht tp : / / s chema s . andro id . com/apk / re s / android"
android : layout_width= " fi l l_pa rent "
andro id : layout_he i ght= " fi l l_parent "
android : orientation= " ho r i z onta l "
android : layout_gravity= " cent e r_vertical l cente r_ho r i z onta l " >
< ImageView
android : id= " @ + id/ image "
android : la yout_width= "wrap_content "
android : la yout_he i ght= "wrap_content "
android : minHe i ght = " l O Opx "
android : minWi dth= " l O Opx "
android : layout_ma rgin= " l O Opx " / >
< / LinearLayout >

:
Animat i on
AnimationU t i l s . loadAnimation ( )


L- . <;
View . s t a rtAnima t ion ( ) , Animat ion:
,

ImageView. image

( ImageView)

findViewByid ( R . i d . image ) ;

Animat ion animat ion


AnimationUt i l s . loadAnima t ion ( th i s , R . anim . a lpha ) ;
image . s t a rtAnimation ( animat ion ) ;

1 8

410

Animat ion
:
D

onAnimat i onEnd ( ) ;

onAnima t i onRepea t ( ) ;

onAnimat ionStart ( ) .

Anima t i onLi s tene r,

,
. ,
, -
:
@ Ove r ride
pulic void onAnima t i onStart ( Anima t i on animation)
mimage . s etVi s i bi l i ty (View . VI S IBLE ) ;

@ Overr ide
pulic void onAnima t i onEnd (Animation animat ion )
mimage . s etVi s ibi l i t y ( View . INV I S I BLE ) ;

@ Ove rride
pulic void onAnimat i onRepeat ( Animat ion animat ion )
mimage . s etVi sibi l i t y ( Vi ew . VI S IBLE ) ;

,
, - Alpha, Scale, Translate, Rotate
Total.
L- ,
onOpt ions i t emSe lected ( ) , .

1 8 . 8 .

TweenAnima t i onActivity

package com . s ample s . tweenanima ionshape s ;


import android . app . Ac t iv i t y ;
import android . os . Bundle ;
import android . view . Mnu ;
import android . view . Menu i t em;
import android . view . View;

411


import android . view . anima t i on . An imat ion ;
import android . view . anima t i on . Animat ionUt i l s ;
import android . view . anima t i on . An imat ion . Animat ionLi s tene r ;
import android . widget . ImageView;
import android . widget . Toa s t ;
pu l i c c l a s s TweenAnimationAc t ivity extends Activi ty
implements An imationListene r {
p rivate ImageView m!mage ;
private Anima t i on anima t i on ;
@ Ove rride
p rotected void onCreate ( Bundle savedins tanceState )
s upe r . onCreate ( savedinstance State ) ;
setContentView ( R . layout . main ) ;
mimage

( ImageView ) findVi ewByid ( R . id . image ) ;

mimage . s et imageRe source ( R . drawale . shape ) ;

@ Ove r ride
pu l i c boolean onCreateOpt ionsMenu ( Menu menu )

menu . add ( Menu . NONE , R . anim . a lpha , Menu . NONE , "Alpha " )
. setAlphabet icSho rtcut ( ' a ' ) ;
menu . add ( Menu . NONE , R . anim . s ca l e , Menu . NONE , " Scale " )
. setAlphabeticShortcut ( ' s ' ) ;
menu . add ( Menu . NONE , R . anim . t rans late , Menu . NONE ,

" T rans late " )

. setAlphabeticSho rtcut ( ' t ' ) ;


menu . add ( Menu . NONE , R . anim . rotate , Menu . NONE ,

" Rotate " )

. setAlphabet i cShortcut ( ' r ' ) ;


menu . add ( Menu . NONE , R . anim . tota l , Menu . NONE , " Total " )
. setAlphabet i cShortcut ( ' o ' ) ;
return ( supe r . onCreateOpt i onsMenu (menu ) ) ;

@ Ove rride
pu l i c boolean onOpt i ons i temSel ected ( Menuitem i tem )

11

L-

animation

An imat i onUt i l s . loadAnima t i on (


thi s , item . get i temid ( ) ) ;

anima t i on . setAnimat ionL i s tene r ( thi s ) ;

1 8

412
m!mage . s ta rtAnima t i on ( an irna t i on ) ;
return t rue ;

11

Anirna t i onLi stener

@ Ove rride
pul i c void onAnirnat i onEnd (An imation animation )
mirnage . setVi s ibi l i t y (View . INVI S IBLE ) ;

@ Ove rride
pul i c void onAnirna t ionRepeat (An irna t i on anima t i on )
m!rnage . setVi s ib i l i t y ( View . V I S IBLE ) ;

@ Ove r ride
pul i c void onAnimationStart (An irna t i on anirnat i on )
m!mage . setVi s ibi l i ty ( View . VI S IBLE ) ;

. ,
.
. 1 8 .3 .

. 1 8.3. L-

413

1 8. 1 . 3 .
, n,
n.
n , ImageView.
Eclipse n n n New And roid
Project:

Project name - TweenAnima t i onView;

Application name - Tween

Package name - com . samp l e s . tweenanimat ionview;

Create Activity - TweenAnimati onAct ivi ty.

Animation Sample;

Resources/Iages/ n-
adroid_ d.png ( , n
n ).
L- no
n n: n <sca l e >
<set>. <set> n
, <scale> < rotate>,
Vi ew, res/anitn/ n
i adroid.xm l .
a im_adroid.xl n 1 8 .9.

< ?xml ve r s i on= " . 0 " encoding= " ut f- 8 "


<set xmlns : android= " http : / / s chemas . android . com/ap k / re s /androi d "
android : sha re!nte rpolator= " fa l s e " >
<scale
android : int e rpolator=
" @ android : anim/ acce l e rate_dece l e rate_ inte rpolator "
android : fromXScale= " l . O "
android : toXScale= " 1 . 4 "
android : fromYScale= " l . O "
android : toYScale= " O . "
android : pivotX= " S O % "
android : pivotY= " S O % "
android : f i l lAfter= " fa l s e "
android : durat i on= " O O O "
<set
android : interpolat o r= " @ android : anim/decele rate_inte rpol ator " >

18

414
<scale
android : fromXScale= " 1 . 4 "
android : t oXScale= " O . O "
android : fromYScale= " O . "
android : toYScale= " O . O "
android : pivotX= " 5 0 % "
android : pivotY= " 5 0 % "
android : s ta rt0ffset= " 3 0 0 0 "
android : dura t i on= " 2 0 0 0 "
androi d : f i l lBe fore= " fa l s e "
< rotate
android : frornDegre e s= " O "
android : t o Degree s= " - 4 5 "
android : toYScale= " O . O "
androi d : pivotX= " S O % "
android : pivotY= " S O % "
android : s ta rtOffset= " O O O "
android : dura t i on= " 2 0 0 0 " / >
</set>
< / set>

n
ImageView, n 1 8. 1 .

< ? xml ve r s i on= " l . O " encoding= " ut f- 8 " ?>


<Linea rLayout xmlns : andro id= " http : / / schemas . android . com/ apk/ re s /android"
android : or ientat ion= " ve rt i ca l "
android : layout_width= " fi l l_pa rent "
android : layout_he i ght= " fi l l_parent " >
<LinearLayout
androi d : layout_he i ght = " w rap content "
android : orientation=" hori zonta l "
android : layout_width= " fi l l_pa rent " >
<Button
androi d : i d= " @ +id/btn s ta rt "
androi d : l a yout_he i ght= " w rap_content "
android : text= " S tart "
androi d : layout_width= " fi l l_parent "
android : l ayout_we i ght= " l " / >
< / Linea rLayout >

415


<Linea rLayout
android : id= " @ + id/layout_anim"
android : layout_he i ght= " fi l l_parent "
android : gravity= " cente r "
android : layout_width= " fi l l_parent " >
< ImageView
android : id= " @ + i d / image "
android : l ayout_width= "wrap_content "
android : layout_he i ght="wrap_content "
android : minHe i ght= " l O Opx "
android : minWidth= " l O Opx "
androi d : layout_ma rgin= " l O Opx "
android : s rc= " @drawa e / androidd " / >
< / Linea rLayout >
< / LinearLayout>


1 8 . 1 1 .

weenAnimati onAct ivity

package com . sampl e s . tweenanima t i onview ;


import android . app . Ac t ivi t y ;
import andro id . os . Bundle ;
import android . view . View ;
import andro id . view . anima t i on . An imat ion ;
import android . view . anima t i on . AnimationUt i l s ;
import android . widget . But t on ;
import android . widget . ImageView;
pu i c class TweenAnimationAc t ivity extends Activity
@ Ove rride
protected void onCreate ( Bundle savedins tanceState )
s upe r . onCreate ( savedinstanceState ) ;
setContentView ( R . layout . ma in ) ;
final Button btnStart

( But ton )

final ImageView image

( ImageView)

findViewByid ( R . id . btn_s t a rt ) ;
findViewByi d ( R . id . image ) ;

btnStart . s etOnC l i c kL i s tene r ( new View . OnCl i c kLi stene r ( )


pu l i c voi d onC l i c k (View v )

416

1 8

Anirnat ion anim
An ima tionUt i l s . loadAn imat i on (
thi s , R . anim . interpolator ) ;
image . sta rtAnimation ( anim) ;

.
Start ,
,
. n . 1 8 .4.

. 1 8.4.

View

n
L- .
, n
, Vi ew, ,
:
.
,
.

417

1 8. 1 .4.
,
. , Linea rLayout,
,
. , IrnageView
extView, . Eclipse
New And roid Project:
Project name - TweenAnima t i onVi ew;
Application name - Tween Anirnat ion Sample;

Package name - com . samp l e s . tweenanima t i onview;

Create Activity - TweenAnima t i onAct ivity.

L- ,
- <a lpha>
<rotate>
<scale> <rotate> .
res/anim/ circle.xm\.
circle.xml 1 8. 1 2 .

< ? xml ve rs i on= " l . O " encoding= " ut f- 8 "


<set xmlns : android= "http : / / schemas . android . com/ap k / re s /android"
android : sha re !nte rpolator= " fa l s e " >
<alpha
android : fromAlpha= " O . O "
android : toAlpha= " l . O "
android : s ta rtOffset= " O "
android : durat i on= " 5 0 0 0 " / >
<scale
android : duration= " 2 5 0 0 "
android : pivotX= " 5 0 % "
android : pivotY= " S O % "
android : fromXS cale= " l . O "
android : fromYScale= " l . O "
android : toXScale= " 2 . 0 "
android : toYScale= " 2 . 0 "
< rotate
android : frornDegree s = " O "

18

418
androi d : toDegrees = " O "
android : pivotX= " S O % "
android : pivotY= " 5 0 % "
android : durat i on= " S O O O "
< s ca l e
android : durat i on= " 2 5 0 0 "
android : st a rt0ffset= " 2 5 0 0 "
android : pivotX= " S O % "
android : pivotY= " 5 0 % "
android : frornXScale= " l . O "
android : fromYScale= " l . O "
android : toXScale= " 0 . 5 "
androi d : toYScale= " O . S "
< s ca l e
android : durat i on= " 2 5 0 0 "
android : st a rt0ffset= " 5 0 0 0 "
android : pivotX= " S O % "
android : pivotY= " S O % "
android : frornXScale= i' l . "
android : fromYScale= " l . O "
android : toXScale= " 1 . 2 5 "
android : toYScale= " 1 . 2 5 "
< s ca l e
android : durat i on= " 2 5 0 0 "
android : sta rt0ffset= " 7 5 0 0 "
android : pivotX= " S O % "
android : pivotY= " S O % "
android : frornXS cale= " l . O "
android : fromYScale= " l . O "
android : toXScale= " O . B O "
andro i d : toYScale= " O . B O "
< / set>

n n
LinearLayout, ImageView
n n n extView n
" Hello, Adroid ! " n
:
android : id= " @ + i d / l ayout_anim,

n n
. n 1 8 . 1 3 .

419

< ?xrnl ve r s i on= " l . O " encoding= " ut f- 8 " ?>


<Linea rLayout
xrnlns : android= "http : / / s chemas . andro i d . com/apk / re s /android"
android : ori enta t i on= "ve rt i ca l "
andro id : layout_width= " f i l l_pa rent "
android : layout_he i ght= " fi l l_pa rent " >
<Linea rLayout
android : layout_height = "wrap content "
android : or i entation= " hori zonta l "
android : layout_width= " fi l l_parent " >
<Button
android : id= " @ + id/btn s t a rt "
android : l ayout_he i ght = " wrap_content "
androi d : text= " Start "
android : l ayout_width= " f i l l_parent "
android : l ayout_we i ght= " l " / >
< / Linea rLayout >
<Linea rLayout
android : id= " @ + id/layout_anim"
android : layout_he i ght= " f i l l_pa rent "
android : gravi t y= " cent e r "
android : layout _width= " fi l l_parent " >
< ImageView
android : i d= " @ + id/ image "
android : l ayout_width= "wrap_content "
android : l ayout_he i ght= "wrap_content "
android : s rc= " @ drawale/andro idd" / >
<TextView
android : id= " @ +id/ text "
android : text= " @ s t ring/he l l o "
android : l ayout_width= "wrap_content "
android : l ayout_he i ght= "wrap_content " / >
< / LinearLayout>
< / Linea rLayout>

n , . 1 8 . 5 .
n n n,
, n

, nn :

420

1 8

layout

( Linea rLayout ) findVi ewByid ( R . id . layout_anim) ;

anima t i on

Anima t i onUt i l s . loadAn imation ( this , R . anim . c i rc l e ) ;


1 8 . 1 4.

weenAnima t i onAct ivity

. 18.5.

package com . sample s . tweenanima t i onlayout ;


import android . app . Ac t ivi t y ;
import android . os . Bundle ;
import android . view . V iew ;
import android . view . anima t i on . Animation ;
import andro id . v iew . anima t i on . AnimationUt i l s ;
import android . widget . But ton ;
import android . widget . Linea rLayout ;
pu l i c c l a s s TweenAnimationActivity ext ends Ac t ivity
private LinearLayout layout ;
private Anima t i on animation ;
@Ove r ride
protected void onC reate ( Bundle savedinstanceS tate )
supe r . onCreate ( savedinstance State ) ;
setContentView ( R . layout . main ) ;

421


layout

( LinearLayout ) findViewByi d ( R . i d . layout_anim ) ;

animation

AnimationUt i l s . loadAnimat ion ( thi s , R . anim . c i rc le ) ;

layout . s ta r tAnima t i on ( animation ) ;


final Button btnS tart

( Button )

findViewByid ( R . id . btn_s tart ) ;

btnStart . se tOnClickListener ( new View . OnCl i c kLi s tene r ( )


pul ic void onC l i c k (View v )

layout . st a rtAnimation ( animation ) ;

.
. 1 8 .6.

. 1 8.6.

1 8 . 2 .
( ) - ,
.
AnimationDrawale.

422

1 8

, , L
res/an im/
Android.

1 8. 2 . 1 . XM L

L-
<animation- l i s t > < i t em>,
, :

L- :
<animation- l i s t xmlns : android= " http : / / schemas . android . com/ apk/res /android"
android : oneshot= " t rue " >
< i t em android : drawae= " @ drawa e / f i l e l

android : duration= " 2 0 0 "

< i t em android : drawa e= " @ drawa e / f i l e 2 " android : durat ion= " 2 0 0 "
< i t em andro id : drawa e= " @ drawale / f i le " android : dura t i on= " 2 0 0 "
< /animation- l i s t >

.
android : oneshot t rue
. android : oneshot
false, . L-,
res/anim/ n,
.
.
Ecl i pse New And roid Proj ect:

Proj ect name -

Application name -

Package name - . samp l e s . frameanimat ionxml;

Create Activity -

FrameAnimat i onVi ew;


Frame Animat ion Sample;

FrameAn ima t ionActivity.

<?xml ve rs ion= " . 0 " encoding= " ut f-8 " ?>


<Linea rLayout
xmlns : android= " http : / / schema s . android . com/apk/ re s / android"
android : orient a t i on= " ve r t i ca l "

423

android : layout_width= " f i l l_parent "


android : layout _he i ght= " fi l l _parent " >
<LinearLayout
android : layout_he ight= "wrap content "
android : orientation= "hor i z ontal "
android : layout_width= " fi l l_parent " >
<But ton
android : i d= " @ + id/btn s t a rt "
android : l ayout_he ight= "wrap_content "
android : text= " Start "
android : la yout_width= " fi l l _parent "
androi d : l ayout_we ight= " l " / >
<Button
androi d : id= " @ + id/btn_stop "
android : l ayout_hei ght= "wrap_content "
android : text= " S top "
android : l ayout_width= " fi l l_parent "
android : l ayout_we i ght= " l " / >
< / Linea rLayout>
< IrnageView
androi d : id= " @ + id/ irnage "
android : layout_width= "wrap_content "
android : layout_he ight= "wrap_content " / >
< / LinearLayout>

android l .png, android2 .png, android . png,


Resources/Images/ , .
, .
3 00 . L- ,
android_anim.xml res/val ues/.
1 8 . 1 6.

<anirnat ion- l i s t xmlns : android= " ht tp : / / schernas . android . com/ ap k / re s /android"


android : oneshot= " fa l s e " >
< i t em
android : drawale= " @ drawa l e / androidl "
android : durat ion= " O O " />

1 8

424
< i tern
android : drawale= " @ drawa l e / android2 "
android : durat ion= " O O " />
< i tem
android : drawale= " @ drawa l e / android "
android : durat i on= " O O " />
< / animat ion- l i s t >


:
ImageView image

AnimationDrawale

( ImageView ) findViewByid ( R . i d . image ) ;

image . setBackgroundRe s ource ( R . anim . android_anim) ;


Animat ionDrawale animat ion


start ( ) s top ( )

(AnimationDrawale ) image . getBackground ( ) ;

Anima t i onDrawale


1 8 . 1 7 .

FrameAnimat ionActivity

package com . s ample s . f rameanimationxml ;


import andro id . app . Ac t ivi t y ;
import android . graphi cs . drawale . AnimationDrawale ;
import android . os . Bundl e ;
import android . view . View;
import android . widget . Button;
import android . widget . ImageView ;
pu l i c c l a s s FrameAnimationAct ivity extends Act ivity
pul i c void onCreate ( Bundle s avedinstanceState )
supe r . onCreate ( savedinstanceStat e ) ;
setContentView ( R . layout . ma i n ) ;
ImageView image

( ImageView ) findViewByid ( R . id . image ) ;

image . setBackgroundResource ( R . anim . android_anim) ;


Anima t i onDrawal e animat ion
(Anima t i onDrawale ) image . getBac kground ( ) ;
final Button btnStart

( Button )

findVi ewByid ( R . id . btn_s t a rt ) ;

btnStart . s etOnC l i ckListene r ( new View . OnC l i ckListene r ( )

425


pu i c void onC l i c k ( View v )
mAnim . s t a rt ( ) ;

final But t on btnStop

( Button )

f i ndViewByi d ( R . i d . btn_s t op ) ;

btnS top . s e tOnC l i c kL i s tene r ( new View . OnC l i c k L i s tene r ( )

pu i c vo id onC l i c k ( View v )
mAnim . s t op ( )

.
, (. 1 8 . 7).

. 1 8 .7.

1 8. 2 . 2 .
,
-
.
Ecl i pse ,
.

1 8

426

New And roid Project:


D Project name -

FrameAnimat ion imageView;

D Application name D Package name -

Frame Animation Sample;

. sample s . frameanimat ionimagevi ew;

D Create Activity -

FrameAnimat ionAct ivi ty.

1 8 . 1 5
. FrameAnima t i onActivity
, start ( ) s t op ( ) ,
onC l i c k ( ) Start Stop.
s tart ( ) .
Drawale,
. Drawale:
Bi tmapDrawa le frame 1
( Bi tmapDrawale ) getResources ( ) . getDrawale ( R . drawale . android1 ) ;
Bi tmapDrawae frame2
( Bi tmapDrawale ) getResources ( ) . ge t Drawale ( R . drawale . android2 ) ;
Bi tmapDrawale frame
( Bi tmapDrawale ) getResources ( ) . getDrawale ( R . drawale . android ) ;

Bi tmapDrawale
addFrame ( ) . addFrame ( )
: ( Drawale)
.
:

AnimationDrawae

Animat ionDrawale mAnimation

1/

new AnimationDrawale ( ) ;

mAnimation . s etOneShot ( fa l se ) ;
mAnimation . addFrame ( f rame 1 , 1 0 0 ) ;
mAnimation . addFrame ( frame2 , 1 0 0 ) ;
mAnimat ion . addFrame ( frame , 1 0 0 ) ;

/1

ImageView

mimage . se tBackgroundDrawale (mAnimation) ;

1 1 Drawae
mAnimation . s etVi s ile ( t rue , t rue ) ;
mAnimation . s t a rt ( ) ;


1 8 . 1 8 .

FrameAnima t i onActivity

427

pac kage com . smples . frameaninimageview ;


import android . app . Ac t ivi t y ;
import android . graphi c s . drawae . Anima t i onDrawa e ;
import android . graphi c s . drawale . Bi tmapDrawale ;
import android . os . Bundle ;
import android . view . View;
import android . widget . Button ;
import android . widget . ImageView ;
pu l i c c l a s s FrameAnimationActivity extends Act ivity
private final s t a t i c int DURAT ION

300 ;

private AnimationDrawale mAnimation

nul l ;

p r ivate ImageView mimage ;


@ Ove r ride
p rotected void onCreate ( Bundle savedinstanceState )
supe r . onCreate ( s avedinstance State ) ;
setContentView ( R . layout . main ) ;
mimage

( ImageVi ew ) findViewByid ( R . id . image ) ;

final Button btnStart

( Button )

findViewByid ( R . id . btn_s t a rt ) ;

btnStart . s etOnCl i c kL i s tene r ( new View . OnC l i ckL i s tene r ( )


pu l i c voi d onC l i c k ( View v )

s t a rt ( ) ;

final Button btnStop

( Button )

findVi ewByid ( R . id . btn_s t op ) ;

btnS top . setOnClickLis tene r ( new View . OnC l i c kL i s tener ( )


pu l i c voi d onC l i c k ( View v )

s t op ( ) ;

private void s t a rt ( )
{
Bi tmapDrawale frame l
( B i tmapDrawale ) getResource s ( ) . get Drawale ( R . drawale . androidl ) ;

428

1 8
B i trnapDrawal e frame2
( B itrnapDrawal e ) getRe sources ( ) . getDrawale ( R . drawale . android2 ) ;
B i trnapDrawal e frame
( B i trnapDrawale ) getRe s ou rce s ( ) . getDrawale ( R . drawale . android ) ;
mAnimat ion

new AnirnationDrawale ( ) ;

mAnirnat ion . setOneShot ( fa l se ) ;


mAnirnat ion . addFrame ( frame l , DURAT ION ) ;
mAnirna t ion . addFrame ( frame2 , DURAT ION ) ;
mAnirnation . addFrame ( f rame , DURAT ION ) ;
mirnage . setBackgroundDrawa l e (mAnimation ) ;
mAnirnat ion . se tVi s ile ( t rue , t rue ) ;
mAnirnat ion . s tart ( ) ;
private voi d s t op ( )
{
mAnirnat i on . s top ( ) ;
mAnirnat ion . setVi s ile ( fa l s e , fa l se ) ;


L- ( . . 1 8 .7 ).

-

-
- : Samples/ Resources/.
Samp les/ , .
Resources :

Ani matio/ - ( 18) ;

l m ages/ -

Meu_lcos/ - (
8) , ( 9) , ( 1 0-18).

Ga l l e r y

( 7) ;

Android SDK.
.


Samples/ - ,
. n Ecl ipse
. n File 1 Switch
Workspace 1 Other Workspace Launcher
,
(. 1 . 1 ).

Adroid S DK. n
Window 1 P references. Preferences
And roid . SDK Location
, Adroid SDK. -

430

Browse Adro i d SDK,


. 1 .2 .
, ,
-.

Select

workspace

Eclipse stores your projects in folder called workspace.


Choose workspace folder to use for this sessn.

!;_ 5engs

. 1 . 1 . Eclipse

General

Build
DDMS
Launch
LogCat
Usage Stats
Ant
Data Management
Google
Help
Instaii/Update
Java
Java
Plugin Development
Remote Systems
Run/Debug
Server
Tasks
Team
Terminal
lf Usage Data Collector
Validation
Web
Web Services
X Doclet
...... ' i. X.oi L...

Android Preferences
:::;i.;:ki..i

of SDK Tari;Jets below i qniy relooded once you hi


. Target Name

Adrid .i :;
Andro1d 1 . 5
1 Android 1 .
' Android 2 . 0
Android 2 . 0 . 1
Google AP!s
. Google AP!s
1 Google AP!s
1 Google AP!s

.. ......

Vendor

;-;;; ' s;";;;


Android Open Source Project
Android Open Source Project
ndroid Open Source Project
Android Open Source Project
Google Inc.
Google Inc.
Google Inc.
Google Inc.

Andr id + Google AP!s

..

. 1 . 2 . Android S D K

'l'

''
.

:. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . : . . . . . . . . .

' Platforin

. . ,

1.1

1.5
1 .
2.0

3
4
5

2.0. 1

1.5
1 .
2.0

3
4
5

2.0. 1

431

File 1 Import Import


Generai/Existing Proj ects into Workspace, . 1 .3 .
Next.

Select

\i
D

Create new projects from an archive file or directory.

. . .. . .. : .. : = .: : =

9- General

@; Archive File

tlli ExistJng Projects lnto Workspace

9 F1le System

:.: .. ;. Preferences

(;- cvs
!i fe, EJB

Java

i'' Plug-in Development

;::;, Remote Systems

i2i7 Run/Debug
[:), Tasks

Team
(& Web
it i2;} Web serv1ces
i

- L

Next >

Cancel

. 1 . 3 .

Select root directory


Samples, -. Projects
, Samples/.
Select , proj ects
into workspace -
, . 1 .4.

: ,
, ,
Ch09_CustomDialog,
CustomDialog.
.

432

Import Projects

Select directory to search for existing Eclipse projects.

0 Selct root directory:

Oseiect chive fde:


eroJects:

ChO:;IIAdid(F:\S; i;\cho_ellod;;d---
ChOS_FrameLayout (F:\Samples\ChOS_FrameLayout)
ChOS_L1nearLayout (F: \Samples\ChOS_Linearlayout)
ChOS_RelativeLayout (F:\Samples\ChOS_RelatlveLayout)
ChOS_TaieLayout (F:\Samples\ChOS_TaieLayout)
ChO_Button (F:\Samples\ChO_Button)
ChO_Checi<ox (F:\Samples\ChO_Checi<ox)
ChO_Chronometer (F :\Samples\ChO_Chronometer)

< ! Se!ect All

"'' j 1 Q.eselec All


.

!1

Refresh

'---":;.;'n;_....J.; 1

Cancel

[J Add project to worl<ing sets

({;1

<

Back

. 1 .4.

AbsListView 1 47

DDMS (Dalvik Debug Mon itor Service) 20


D igitalCl ock 1 3 3
Draw 9-patch 23

Activity Manager 1 3
AdapterV i ew 1 46, 1 47
Adnroid S D K 1 8
Anal ogC lock 1 3 3
A ndro i d Development Too l s 1 6- 1 9
A ndroid Power Management 9
Andro i d SDK 1 7
A ndro i d V i rtual Device 2 1 , 23
AndroidMan i fest. x m l 50
Applicati o n Launcher 3 8 0
A rrayAdapter 1 47
VD Manager 1 8 , 23 , 24, 26

B roadcastRecei ver 2 8 6 , 289


Bund1e 2 5 3
B utton 98, 9 9

Eclipse 1 5-20 , 22, 24, 3 1


EditText 90
Ed itextPreference 3 0 2
Explorer V i ew 83

F
Frame an i m ation 40 1
FrameLayout 6 8 , 92
FreeType 1 2

G
Gal lery 1 46, 1 6 1
G r i d V i ew 1 46 , 1 5 3 , 1 5 7

CheckBox 9 8 , 1 0 9

CheckBoxPreference 3 0 2

H i e rarchy V i ewer 2 3 , 8 1

Chronometer 1 3 3 , 1 3 5

H om e screen 26

Content Providers 1 3

H orizontai Scro i i V i ew 92

ContentProvider 1 3 , 3 2 8
Context M e n u 225
Cursor 1 47, 325
l mageB utton 98, 1 1 5

I mage V i ew 95
l ntent 25 5

Dalvik Debug Mon itor Service 22

l ntentF i lter 27 1

Dalvik V i rtual Mach i n e 1 2

lterator 3 3 3

434


Resource M anager 1 3
R i ngtonePreference 3 02

J ava Runti m e Environment 1 6

L
Layout Ed itor 63

s
Scro i ! V iew 92
SecurityExcepti on 279

Layout V i ew 8 2

SeekBar 1 20 , 1 25

I ayoutopt 23

SGL 1 2

Iayouts 6 1

Shared Preferences 3 0 3

LinearLayout 6 8 , 1 00

S i mp1eAdapter 1 47, 1 70

Li stActivity 1 4 7

S i mpleCursorAdapter 1 70

Li stPreference 3 0 2

S 1 i d ingDrawer 1 46 , 1 6 5

ListView 1 46- 1 48

Spi nner 1 46 , 1 49

Loupe Y i ew 83

SQLite 1 1
sq1 ite3 23

M e d i a Fram ework 1 1
mksdcard 23

S Q L iteDatabase 3 2 5
SQLiteOpenHelper 3 2 3
SSL 1 2
Status Notification 1 7 5
Stri ng 90

N
Normal broadcasts 2 8 5
Normal Y i ew 8 3

TabH ost 1 1 7
Ta \ eLayout 6 8 , 74

Tab W i d get 1 1 7
Text V i ew 8 5 , 86, 95

on Draw() 3 9 4

Toast Notificati o n 1 7 5- 1 7 8

OpenGL ES 1 1

ToggleB utton 9 8 , 1 1 2

Ordered broadcasts 2 8 5

Package M anager 1 3
Pai ntDrawa \e 3 5 0

Traceview 23
Tween A n imation 40 1 , 40 5 , 4 1 3 , 4 1 7

u
U R I 2 5 5 , 327

P i xel Perfect V i ew 8 1 , 8 3
Preferences 295
ProgressBar 1 2 0- 1 22
Properties Y iew 8 3

v
Y i ew 6 1 , 66
Y i ew System 1 4

R
Rad i oB utton 9 8 , 1 06
RatingBar 1 20 , 1 3 3

Y i ewGroup 6 1 , 66

RelativeLayout 6 8 , 7 8

WebKit 1 2

Request Layout 8 3

W i n dow Manager 1 3

435

1 3 9

)> 275

226

46

226

349, 373

1 3 9

3 5 0

1 8 5

404, 405

S Q L ite 3 2 3
B i o i c 1
1 3

1terator 3 3 3

O C 1 ick L i steer 9 8

OCreateCotext M en u L i steer 9 8

On FocusChangeLi stener 9 8

OnKey L i steer 9 8

On LongC i ickListener 9 8

OnTouch L i stener 9 8

8 5
47
Dalvik 1 2
1 7 5

226, 227
N i n e Patch 3 5 0 , 3 5 1
3 5 0

6 1
4 0 5 , 408

244

6 1

2 5 5
4 3 , 249
1 9 1
X M L 3 6 4

3 6
2 5 5

A l ertDialog 1 93

A 1 phaA i mation 40 1

A al ogC iock 1 3 3 , 1 34

A i matio Drawa l e 42 1 , 424, 426---4 28

A n i m atio Set 40 1 , 404

A rcShape 3 8 7 , 3 8 9 , 3 9 0 , 392, 3 9 5 , 3 9 7

A rrayAdapter 1 40

A rray Li s t 1 70

A s setM aager 349, 3 7 3 , 3 7 5

A utoCo m p l eteTextV i ew 1 40

B roadcastRece i ver 2 8 5-2 8 7 , 2 8 9-29 1

Budle 253

B utton 99

Calen dar 2 1 6

CheckBox 1 09

CheckBoxPreferece 302

Chronom eter 1 3 3 , 1 3 5

I P C 9

CotetProvider 3 26-3 29, 3 3 1 , 3 3 2 ,


340, 34 1

2 5 6

Co ntetRes o l ver 3 2 7-3 29, 3 3 1 , 3 3 2 ,


334, 335

CotetV alues 3 2 5 , 3 2 6 , 3 3 0 , 3 3 4 , 3 3 8340, 342, 343 , 3 4 5 , 346

226

Cotext 1 3 9 , 295

3 2 7 , 332

Cursor 325

436

(.)

S i m p l eC u rsorAdapter 1 47 , 1 70

CursorA d apter 1 47

S l i d i ngDrawer 1 5 7, 1 64

DatePi ckerD ialog 2 1 1

S p i nner 1 49

D i g itaiC iock 1 3 3 , 1 3 4

S Q L iteDatabase 3 2 5

Drawa ie 3 8 1 , 3 8 3 , 3 84, 3 87 , 3 8 9, 394

S Q L iteOpen H e l per 3 2 3

EditText 8 5

String 90

EditTextPreference 3 0 2

Tab H ost 1 1 7

Tab W i dget 1 1 7

F i l e l n putStream 295

F i leOutputStream 296

F rameLayo ut 92

G a l l ery 1 5 7 , 1 6 1

GridV iew 1 5 3

H ashMap 1 7 1

Horizontai Scro i i V iew 92

1 m ageB utto n 1 1 5

l m ageY i ew 95

l ntent 1 8 2, 2 8 5--2 87, 2 8 9--293

I ntentF i lter 27 1

Layoutlntlater 1 79

L i stAct i v ity 1 47 , 1 4 8

L i stAdapter 1 4 7

L i stPreference 3 0 2

L i st Y i ew 1 47

1 70, 3 2 6 , 3 3 4

M e n u l tem 226

M u l t i A utoCo m p l eteTextY i ew 1 43

Notificati o n 1 83

NotificationManager 1 83

PaintDrawa ie 3 5 0

Path 3 8 8

Pen d i ngl ntet 1 84

ProgressBar 1 20 , 1 2 1

Text V i ew 8 5

TimePickerDialog 2 1 6

Toast 1 79

ToggleB utton 1 1 2

Tran s i tion Drawaie 3 84

TranslateA n i m ation 402

Typeface 3 7 5 , 3 76

Y i ew 6 1 , 3 9 8

Y i ewGroup 6 1

R 3 9 , 349, 3 5 2

1 6 1

402

ACTI ON_B OOT_COM P LETED 2 8 7

A CT I ON_C A L L 2 5 5

ACTI ON_C A M E R A_B UTTON 2 8 7

ACTI ON_DATE_C H A N G E D 2 8 7

ACTI ON_E D I 2 5 5

A C T I ON M A I N 2 5 5

A C T I ON - S C R E EN -O F F 2 8 7

A C T I ON S YN C 2 5 5

ACTI ON_T I M E_C H A N G E D 2 8 7

Progres s D ialog 206

A C T I ON _T I M EZON E_C H A N G E D 2 8 7

Rad i o B utton 1

CATEGORY _B RO W S A B L E 2 5 6

RatingBar 1 20 , 1 29

CATEGORY _ 2 5 6

RectShape 3 8 7, 3 90--3 9 2 , 3 94--3 97

C A T E G O R Y_LA UNC H ER 2 5 6

R i n gtonePreference 3 0 2

LENGTH LONG 1 76

Rotate A n i mation 40 1

L ENGTH_SH ORT 1 76

Round RectShape 3 87 , 3 8 8 , 390, 392,

NOTI F I C A T I ON_S E R V I C E 1 84

395, 397

R E S U LT_CAN C E L E D 2 5 8

ScaleA n i matio 402

R E S U LT_F I R ST_U S E R 2 5 8

Scro i i Y i ew 92

R E S U L _ 2 5 8

1 46

SeekBar 1 20 , 1 25

Service() 276, 277, 279, 2 8 0

ShapeD rawa ie 3 8 1 , 3 86--392, 3 94--3 9 8

409

S i m p leA dapter 1 4 7

1 76 , 1 84

437


2 2 5 , 2 3 7

-n 1 3 , 4 3 , 4 5 , 3 2 3 , 326

onCreateDialog() 1 92 , 207

onCreateOptionsMenu() 226


3 7 7
377

40, 369, 3 70

n 3 72

onCreate() 2 5 0 , 25 1 , 275 , 276, 3 2 4

onDestroy( ) 2 5 0 , 2 5 3 , 275 , 276

o n l temSel ected() 1 5 5

onNoth ingSel ected() 1 5 5

onOpti onsltemSelected() 227, 229, 232,


234, 2 3 5 , 242, 245 , 247

on Pause() 2 5 0 , 2 5 2

onPrepareDialog() 1 93

on ProgressChanged() 1 26

onReind() 277

on Rece ive() 2 8 6 , 287, 289-29 1

onRestart() 2 5 0 , 25 1

on Restore l nstanceState() 2 5 3
on Resume() 2 5 0 , 25 1
on Save l n stanceState() 2 5 3

1 3

n 1 4

1 3

n 1 3

n 1 , 1 1

on Start() 2 5 0 , 25 1 , 275

1 3

on StartTrackingTouch() 1 26

1 4

onStop() 2 5 3

2 2 5 , 3 5 0 , 3 60-3 64, 3 6 9

on StopTracki ngTouch() 1 26

onUnind() 277

n 226

onUpgrade() 3 2 4

2 2 5 , 2 3 0 , 23 1

open F i l e l nput() 297

open F i l eOutput() 297

addCategory() 256

q uery() 3 2 5 , 3 2 6 , 329, 3 3 2

i nd Serv i ce() 276

removeCategory() 2 5 6

delete() 3 2 6 , 329, 3 3 0 , 3 34, 3 3 5

send B roadcast() 2 8 8

getCategories() 2 5 6

setChecka e() 244

getlte m l d() 227

setltems() 200

getOnChronometerTickLi stener( ) 1 3 5

setM ultiChoiceltems() 203

getPosition() 3 3 3

setOnChronometerTickLi stener() 1 3 5

getext( ) 90

setO n C i i ck L i stener() 1 1

getype() 3 2 9

set0n 1te m S e l ectedListener() 1 5 5

i nsert( ) 3 2 5 , 326, 329, 3 3 0 , 3 3 4

setS i ngleC h o i ce l tems() 200

i nval idate() 3 94

showDial og() 1 92

makeText() 1 76

startServi ce() 2 7 5

m oveTo F i rst() 3 3 3

m oveTo Last() 3 3 3

stopServ i ce() 279

moveToNe xt() 3 3 3

update() 326, 329, 3 3 0 , 3 3 4

moveToPosition() 3 3 3

m oveToPrevious() 3 3 3

onActivityResu lt() 2 5 8

onBind() 277

2 5 7

onContextlte m S e l ected() 2 3 7

2 8 5

4 9 , 2 5 4

438

n
394, 3 9 8 , 399

1 40

r A DT 20, 35

1 4

240

349, 3 5 0, 3 6 8--3 70, 3 73

333
42 1

/> 2 7 5
92
2 8 5
2 9 5 , 3 0 1
6 1 , 3 9 8
402

43 , 44, 2 8 5

1 75

1 82

API 2 1

r 7, 9

45

244
47

6 2
22 5 , 2 3 3 , 2 3 6
349, 3 7 7
3 9 3

1 3 9
47

1 4

r 9

1
1 3 9

R .j ava 3 8

5 0

27 1
2 5 6
1 83
47
/++ 1 0

2 8 8

4 3 , 44

2 5 7

1 47

A ndroid 7

2 5 4
3 5 0 , 3 6 8

Go
d
r
nr
N

6n

.n11

All nn
nn Google Android
r ano All e ceii .. . . . . " . . . .. ,
.
,
.

J 60 000 did- ,
. . . . , . . .
Android ! 2 20 1 2

(Eric Schmidt), Google


( Moblle World Cogress 20 1 0 , )


,
, ,
-
- .

Goog le Ad roid .
C D - R O M

. ,
, ,

J ava #. N .

i$jiiei0jkl

I S B N 978-5-9775-0562-8

-d

-111&,

1 90005,

-,
., 29

E-mail: maillibhv.ru
lntemet: www.bhv.ru

. : (81 2) 251 -42-44


: (81 2) 320-01 -79

Вам также может понравиться