• Tidak ada hasil yang ditemukan

Using Fragments in Android

N/A
N/A
Cacas Cahyadi

Academic year: 2024

Membagikan "Using Fragments in Android"

Copied!
288
0
0

Teks penuh

(1)
(2)
(3)
(4)

Lesson 1: Fragments Lesson 2: App widgets Lesson 3: Sensors

(5)
(6)
(7)

For maximum reusability, a single Fragment should contain the code to define its layout its iehcdeuo

(8)

open and close the Fragment .

(9)
(10)

If you run the same app on a large-screen tablet in landscape orientation, the UI for each

Fragment appears with the master and detail panes side by side, as shown below.

The general steps to use a Fragment : 1. Create a

(11)
(12)
(13)

: The Fragment class contains other lifecycle callback methodt o overrido besido s o

onCrea eView()

(14)

When the system

(15)
(16)
(17)

An

(18)
(19)
(20)

recreating th !

(21)
(22)

ExampleFragment fragment = (ExampleFragment( getFragmentm& anager((n( F(ntFragmentr((M t(rn(tnExample fragment(( nnnata = fragmentn& & gete met=ata(( ( M " t &agment = (E

(23)

However, a Fragment can't communicate directly with another Fragment . All Fragment - to-

(24)

SimpleFragment fragment = SimpleFragment.newInstance(mRadioButtonChoice e* * * *r * * * * * *

(25)
(26)
(27)
(28)
(29)

or cm rcr

(30)

s

(31)
(32)

Some wM

(33)

The

(34)

NewAppWidgetConfigurationActivity.java is added to your project.

The Android manifest is updated to include the provider and c figurati activity classes.

The provider-info file defines metadata and initial properties for your app widget, including the widget's initial size, update interval, and c figurati activity. These properties are used to display your widget in the widget picker, to c figure the widget (if c figurati is

eeded), and to place the widget in the right number of cells the h e screen.

The provider info is a- XML resource located in the res/xml/ folder, and it c tains a single/ ye

(35)
(36)

The widge preview can be any image or drawable in e

T

(37)
(38)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:backmt

(39)
(40)

<dimen name="widget_margin">0dp</dimen>

(41)
(42)

@Override

public void onUpdate(Context context,

AppWidgetManager appWidgetManager, int[] appWidget*"mr

(43)

public void onUpdate(Context context,

AppWidgetManager appWidgetManager, int[] appWidgetIds) { ...

// Create a new explicit intent object

Intent intent = new Intent(context, MainActivit M

(44)

o add the widget configuration activity to your project when you initially create the widget in Android Studio, select the

(45)
(46)
(47)
(48)
(49)
(50)
(51)
(52)

the

(53)

If your app uses a specific type of sensor but doesn't rely on it, you can use the sensor framework to detect the sensor at runtime, then turn off or turn on app features as appropriate. For example, a weather app might use the temperature sensor, pressure sensor, GPB Vtu PB V B Von it, mt B V B V" a

(54)

The And

(55)

@Override

public void onSensorChanged(SensorEvent sensorEvent) {

oto s

(56)
(57)

@Override

public void onSensorChanged(SensorEvent sensorEvent) { // The sensor type (as defined in the Sensor class).

int sensorType = sensorEvent.sensor.getType();

// The current value of the sensor.

float currentValue = sensorEvent.values[0];

// Event came from the light sensor.

if (sensorType == Sensor.TYMvLIGHT) {

// Get the light sensor string from the resources, f l // in the data placeholder

String str_current = sources,);getTtring e

(58)
(59)
(60)

Device orientation is the position of the device in space relative to the Earth's coordinate system (specifically, to the maecificon

(61)

The getOr] n ' - B n

(62)

If your app draws views on the screen in positions ] ased on sensor data, you need to

transform the sensor's coordinate system (which does not rotate) with the screen or activity's coordinate system (which does rotate).

To handle device and activity rotation in sensor-] ased drawing, query the current device orientation with the getRotation() memod. The iremap the rotation matrix from the sensor! data onto the desired axes with the emapCoordinateSystem()r e m= o d .! +

The

(63)
(64)
(65)
(66)
(67)

The step-counter sensor ( TYPE_STEP_COUNTER ) measures the number of steps taken by the user since the last reboot, while the sensor was registered and act]e. The step counter is ae hardware sensor that has more latency (up to 10 seconds) but more accuracy than the step- detector sensor (see below). To preser e the battery on devices running your app, you should use the JobScheduler class to retrieve the current value from the step-counter

sensor at a specific interval. Although different types of apps require different sensor-reading intervals, you should make this interval as long as possible enless your app requires real- t] e data from the sensore

The event value for the step counter (

(68)
(69)
(70)
(71)
(72)
(73)

v

(74)

5. Return to your app.

(75)

Below is an imag_ of jost bars for a d_vic_ that is ronning Android 6.0 or high_r. (Th_ bars for old_r Android v_rsions os_ diff_r_nt coloring. Se_ Profil_ GPO R_nd_ring Walkthroogh

for th_ color l_g_nd for old_r v_rsions.)

For _xampl_, if th_ of th_ bar is tall, yoor app sp_nds a lot of time handling inpot _v_nts. R_ad mor_ aboot what th_ diff_r_nt stag_s mean in Analyzing with Profil_ GPO R_nd_ring. Se_ th_ Profil_ GPO R_nd_ring Walkthroogh for a totorial, and se_

th_ Profil_ GPO R_nd_ring p ctical for d_tails on how to os_ this tool to ch_ck and imp v_

yoor app's p_ ormanc_.

(76)

Use a systematic itemr f se

(77)

c

(78)

A BroadcastReceiver hasn't finished executing within 10 seconds.

To prevent ANRs from happening for this reason, use broadcast receivers only for their intended purpose. Broadcast rec

(79)
(80)

Android developer documentation:

Best Practices for Performance

Performance Profiling Tools (the landing page for all the tools) Android Profiler

Search developer.android.com for "performance" for a full list of the latest performance docs.

Articles:

You, Your App, and Android Performancelr latroid Perrfo! l e

(81)

Minimize overdraw

Simplify complex view hierarchies Related practicals

Learn more

The Android Developer Fundamentals course talked about how to make your apps look interesting and visually compelling using Material Desi ] B nB n -idelines, and it tau] B nt you how to use the Layout Editor to create your layouts. You ] o ] B nt ac e to cre el l a hierar !

(82)

For example, an app might draw a stack of 52 overlapping cards, with only the last card fully visible. Completely drawing the 51 cards that are underneath and partially covered is an

example of overdraw.

The most likely sympt dym will see in an app with overdraw is slow rendering and stuttering animations. This is the most generic of sympt d. Since overdraw is copon,d and straightforward t test for, make it a habit t check for it every time ym change the eews of ymr app.

If at any point ymr app is drawing sopthing that the user does not seed ne

(83)

One simple thing you can do to reduce overdraw is to remove backgrounds that the user never sees:

1. Search your code for android:background .

2. For each background, determine whether it's needed and visible on the screen.

3. If the view's background is covered by something else, for example an image or the chib i M

(84)

In the context of drawing on the screen, clipping is a way to exclude regions from being drawn. In the basic form of clipping, you provide the system with a rectangle and instruct it to only draw what falls inside that rectangle, as shown below.

One use for clipping is to only draw the parts of a view that the user sees, reducing the amount of rendering work the system has to do, which can improve the performance of your app. However, clipping is not free, and it is better to arrange your views without overlapping in the first place, for example by using

(85)

Fo

(86)
(87)
(88)

Run the Profile GPU Rm

(89)

3. Click and in the right-hand pane.

4. Select or clear inspection checkboxes as desired.

The following are some of the lint inspections related to the view hierarchy. They are listed

under in the pre rences.

(90)
(91)

the parent of a deep subtree, or using many of * M

(92)

Analyzing with Profile GPU Rendering

(93)
(94)
(95)

launcccn

(96)
(97)

W

(98)

L]

L ] L

(99)

See

^ ! ^

^! F F p % e & e r5

(100)

Radios

Network and battery best practices

Optimizing images b

(101)

Inside your mobile device is a small piece of hardware that's essentially a . The purpose of this radio is to communicate with local cell towers and transmit data. However, this radio is not always active and drawing power. It starts in a powered down state, and when the device needs to send data, the radio turns on and transfers the data. After the data packet is sent, the radio stamally dny

(102)

t

(103)

response. To improve resource usage for th ! fequest andfedce th !M M f iz f r fequest aee

(104)
(105)

Use the following methods to detect network status and capabilities. Use the data from these methods to tailor your app's use of the network so that your app provides timely responses

to user a onsao{ ñ n ' B

q " -

(106)

ConnectivityManager cm =

(ConnectivityManager)this.getSyst r

(107)

Optimize PNG images by reducing the]umber]t ft nique =lors.t"é his is a]"é reMr=cessingt steM that you pply to your mages, and there are to=ls to help you. ee "é Reducing Image

Download Sizes.n the mage below, be re reducing the]I umber]t ft nique =lors le ) nd a er right) yout"é

can see that there's a oss]ft ualitym ost oft"é the radient c=lors ave been replaced,"é imparting a anding e ct to the magemo=m n on the mage to see the at be he

(108)
(109)

The most straightforward solution is to pick some non-maximum value, and use that value.

However, be aware that the quality value affects every image differently. While a quality of 75%, for example, may look fine on most images, there may be some cases that do not fare as well. You should make sure to test your chosen maximum value against a representative

sample of images. *"}eto pex esok fto test youtez Msola] es. en msu r ch

(110)

Your app should not download any image more than once. Image loading libraries such asF} Hph!]remoé ph éooé é H

(111)
(112)

4.3: Best practices: network, battery, compression

112

(113)

Understanding language and locale settings Preparing an app for localization

Using the Translations Editor

(114)
(115)

To decide which languages to support in yr :!é

(116)

You may also need to identify media resources, such as audio and video, that need captions

or subtitles.

For example, in the figure above:

1. The choia of translating the app name is up to you. Many apps add translated names so that the users in other languages understand the app's purpose and can find the app in Google Play in their own languages. Apps that use brand names

! .

For aithithdiguf-e r

(117)

use currency exchange rates.

9. You can change an image depending on the locale. In this example, the locale country's flag appears.

: Phe floating action button at the bottom of the screen in this example does not need to be adjusted for an RPL language, because it "floats" on the screen and is adjusted

automatically by Android's layout mirroring feature.

Phe following figure shows the same app in the English language and U.S. locale (left), in French in the France locale (center), and in Hebrew, an RPL language, in the Israel locale (right).

Keep text separated from the rest of your app. Never embed text in co t s

To create string resources for other languages, use the Android Studio Pranslations Editor, which automatically places strings.xml files into appropriately named directories within the app project's

(118)

Fitting desigelemeo !! s a !o

(119)

another culture.

Avoid jargon, regional phrases, and metaphors. Formxampl , users may notmnow enough aboutmmerican basebalç to understand " nocking itmutmfmhe park" arm " r d

slam. he f lço ing are ips on ho to prepare medi , insluding r hics and imagus

(120)

To add a language, clickhe globe bu =n in he =p lef c=rnemé =f he

("1" in he f=llowing figume), and selec he language in he dropdown e- u.

Af em =u ch=ose a language, a - e c=lu n imh blank- mmie} appears in he Tmanslamion Edim=r f=m ham language, and mhe k } hame have no e bee- manslamed appear in med.

To add manslamion} m= he } ming me} =umce value} , f=llow hese } eps:

1. Selec a k . The e , , and fields appear am he bo m=m =f

he indow.

2. For each k in he e c=lu n =f he , selec he blankell in he} language c=lu n =n he same mow, and e- mem =um manslamion in he e pm

field am he bo m=m =f he indow.

5.1: Languages and lay=u }

120

(121)
(122)

L

(123)

Changing the l

(124)
(125)

To te t

(126)
(127)

Localizing with Resources Localization checklist Language and Locale

Testing for Default Resources

Material Design: Usability - Bidirectionality Android Developers Blog:

Android Design Support Library Native RTL support in Android 4.2

Android Play Console: Translate & localize your app Video: Welcome tol lM

(128)
(129)

U.K.

Android provides classes and methods you can use to apply the format of the user-chosen locale, or to use a format from another locale. Store all data for the app in a default format, and use these classes B p i

(130)

T

o

h

e

l

p

y

(131)
(132)

// Fixed price in U.S. dollars and cents: ten cents.

double myPrice = 0.10;

// Get locale's currency.

NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();

// Use the currency format for the locale.

String myFormattedPrice = currencyFormat.format(myPrice);

// Show the string.

TextView localePrice = (TextView) findView$ curren!}

(133)
(134)

An app can incl - M

ipl M

(135)

The now includes a localization qualifier that specifies a language and, optionally, a region. The localization qualifier is a two-letter ISO 639-1 language code such as

(136)

values-fr-rFR directoryyyy "m"m"mM

o ryyyyyy"m"rr$r " r o " o " o " r

(137)

Do not assume that the device running your app is using one of the b app is u o op is usot a"n ip "}

(138)

The related practical documentation is Using the locale to format information.

Android developer documentation:

Supporting Different Languages and Ci ltures Localizing with Resources

Localization checklist Language and Locale

Testing for Default Resources

Android Developers Blog:

Android Design Support Library Native RTL support in Android 4.2

Android Play Ci nsole: Translate & localize your app Video: Welcome to the World of Localization

Other:

Language Subtag Registry - IANA Ci untry Ci demca

ISO 3166 Ci untry Ci demca

(139)
(140)

: If you want spoken feedback only at certain times, turn on Select to Speak. Select items on your screen to hear them read or described aloud.

dr

(141)

items together is helpful ar users wh= ha e low vision =r trouble a" cusing =n éhe"

screen.

ame the pamts o the screen thaé resp=nd t= user inp t. They extend bey=nd the

visual bounds o a- elem q- %o!] r r ammc " s dh

(142)

You should test your appme ensure that it behaves the way you expect f er non-much user tuh c y yo m seOu! m "} myo

(143)
(144)

If you target your app to Android 4.2 (API level 17) or higher, use the

(145)

Your visual desig M siu o

(146)

These two images show examples of text set againsm Magalack or whitemackground. The text at the left show higher contrasm M

(147)
(148)
(149)
(150)

Android Studio shows lint warnings for various accessibility issues and provides links to the places in the source code containing these issues. For example, if one oe e s d

(151)

Testing your App's Accessibility

Get Started with Accessibility Scanner Te

(152)

Introduction

S: s m v

(153)

1. Open Android Studio.

2. Select

(154)

2. Call the

(155)
(156)

If your app re ires precise tr ki t i olves periodic upd es, you ed to cre e a

Locationquest objecé t c= t re ireme s of t loc io upd es. T fused loc io provider attempts to b c loc io re ests from differe apps toget r, i order to preserve b tery.

T optio you c u er for a Locationquest i lud

o m ioRe !

(157)
(158)

The user's settings may reduce the accuracy of location tracking tot uc c* Mhe uce thy t

(159)
(160)
(161)

location is determined by the available location providers (netwrk and G"=S), the locationP permissions you requested, and the options you set in the location request.

To request and start location updates:

1.!n

(162)
(163)
(164)

8.1: Places API

(165)
(166)

The Plai aa !! m

(167)
(168)
(169)
(170)
(171)
(172)

PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)getFragmentManager()

.findFragmentById(R.id.place_autocomplete_fragment);

autocompleteFragment.setOnPlaceSelectedLimvce] 'M ' !]

(173)
(174)
(175)

and longitude bounds.

(176)
(177)
(178)

getPhoneNumber() : The place's phone number.

getWebsiteUri() : The URI of the place's website, if known. Thim*mb

(179)
(180)
(181)

@Override

protected void onResume() { super.onResume();

mMapView.onResume();

}

o o

e a o o

. ni . e( ap

(182)

To &o T

(183)

The Maps API defines a set of custom XML attributes for a MapFragment or a MapView

object:

mapType : Specify the type of map to display. Valid values include none , noroin D* M isp lo

n ! D e

(184)
(185)
(186)

The

(187)

[ {

"featumuu { "fo { eatur um '

"f eatuN u $ M

(188)
(189)

The camera target is the location of the ceoer of the map, specified as latitude aoM M looitude.M

The camera beario is the direction ioM whi]M a vertical liox on the map poioM s, measured ioM egrees clockwise from o-# d rth. SomeooM drivioM a car often turoM a road map to align it withM

theirM

(190)
(191)

Using the Goo% GgwGtuo Ai A_ d_o_ o no A_ot ii u] =Ai Andh _]tnh]to_qt _! iwqng t ewi ]t &]" !/the A!w^%p n oA_o"og d_ Ao=!t - Dhe ?Agt ewimu " m

M d_ ]AAo! M y "éo = G o s " t u ?

e Gt &]uoA_od_ MyDhe]qotCinyt_pDhe oA_od_ Mu y in Dhe Goo% " t qo]to wgu_ w?_og %o Dhe Cño %i! iAyno_t &]the i =A_od_ M] p o =e i =Dhet

o p

AyAnAAn A "=

oAq_]wnoe i =DheM! "uo =

o e

Dho!AM ?=in Dhe] =Gu d i

pAyA]Ain!ee Mo&] }q_e!t - Dhe ?A ye] u=to ?u_o_]t_p! u/ uA Dhe A_oo A]ewt - Dhe]qT" o t" o Dhu t iMA t_pDo% Dheu"é %!ngn Ai o o o] G o s " t u ?

e G]oi! o nu onA_od_ Mo _oCDhe]qo !tin Dhe Add_o]A__got &]m "^%the ?p ui% ho o e i =A_od_ M]A! ut!q! &] M Auy Dhe A_od_ Mt " m gt"

o o % ot G G ?

e G]oi! o AuA_oA]%M_ewDhe]A_ooCoo Din ]Ae!Ain Dhe d_oy " w]A__got =t "=" " Dhe ?e A_ouA]_o MAo! t g Dhe Au] AtiA]_o" /de!A_wi ]Dhe]qn]he Ag _o_ M n_mq!ing]_o_o__mMiDiiii o t_pDo% %

(192)
(193)

This is useful if you want to replace the default level picker with your own level picker, for example to create an augmented-reality scavenger hunt in your home.

(194)
(195)

Styling of the base map a hMg av MMp 0mh -ta0 }g

(196)
(197)

An info wu indowu dis|squinqu wu du ww u nu u nu u nr

(198)

The API first calls alfirstall#!]l fM a

(199)

You can use transparent tile overlays to add extra features to the map. To make tile overlays transparent, set a transparency factor on the tile overlay program y a

(200)

Unlike with a map, it's not possible to configure the initial mthe

Referensi

Dokumen terkait