Android Unit2
Android Unit2
This work
This work is licensed under is licensed
a Creative under
Buttons anda Creative
B uttons and
Android Developer Fundamentals V2 c lickable imag es
Commons Attribution 4.0 International 2
International License.
Us ers expect to interactwith apps
1. Right-click app/res/drawable
2. Choos e New > Image As set
3. Choos e Action Barand Tab Items
from drop down menu
4. Click the Clipart:image Experiment:
(the Android logo) 2. Choos e New > VectorAsset
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});
<ImageView
android:layout_width="wrap_content" android:onClick
android:layout_height="wrap_content"
android:src="@drawable/donut_circle"
android:onClick="orderDonut"/>
For example:
Add Contactbutton in Contacts app
● 56 x 56 dp by default
● Set mini size (30 x 40 dp) with app:fabSize attribute:
○ app:fabSize="mini"
● Set to 56 x 56 dp (default):
○ app:fabSize="normal"
1. EditText
2. SeekBar
3. CheckBox
4. RadioButton
5. Switch
6. Spinner
● Activity.getCurrentFocus()
● ViewGroup.getFocusedChild()
● EditText default
● Alphanumeric keyboard
● Suggestions appear
● Tapping Return (Enter) key s tarts
new line
Return key
This work is licensed under a Creative
Android Developer Fundamentals V2 I nput Controls Commons Attribution 4.0 International 36
License.
Customize with inputType
Emoticons
This work is licensed under a Creative
Android Developer Fundamentals V2 I nput Controls Commons Attribution 4.0 International 38
License.
EditTextfors ingle line
● Both work:
○ android:inputType
="textLongMessage"
○ android:inputType
="textPersonName"
● Single line of text
● Tapping Donekey advances focus
to next View Done key
This work is licensed under a Creative
Android Developer Fundamentals V2 I nput Controls Commons Attribution 4.0 International 39
License.
EditTextforphone numberentry
● android:inputType ="phone"
● Numeric keypad (numbers only)
● Tapping Donekey advances focus
to next View
Done key
This work is licensed under a Creative
Android Developer Fundamentals V2 I nput Controls Commons Attribution 4.0 International 40
License.
Getting text
● Spinner
Toggle buttons
Switches
1. Alert dialog
2. Date picker
3. Time picker
1 2 3
<item android:id="@+id/option_settings"
android:title="Settings" />
<item android:id="@+id/option_favorites"
android:title="Favorites" />
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
<item
android:id="@+id/action_favorites"
android:icon="@drawable/ic_favorite"
android:orderInCategory="30"
android:title="@string/action_favorites"
app:showAsAction="ifRoom" />
1. Create XML menu resource file and assign appearance and position attributes
2. Register View using registerForContextMenu()
3. Implement onCreateContextMenu() in Activity to inflate menu
4. Implement onContextItemSelected() to handle menu item clicks
5. Create method to perform action for each context menu item
<item
android:id="@+id/context_share"
android:title="Share"
android:orderInCategory="20"/>
This work is licensed under a Creative
Android Developer Fundamentals V2 I nput Controls Commons Attribution 4.0 International 67
License.
Register a view to a context menu
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_context, menu);
}
In onCreate():
View view = findViewById(article);
view.setOnLongClickListener(new View.OnLongClickListener()
{
public boolean onLongClick(View view) {
if (mActionMode != null) return false;
mActionMode =
MainActivity.this.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
}); This work is licensed under a Creative
Android Developer Fundamentals V2 I nput Controls Commons Attribution 4.0 International 76
License.
Implement mActionModeCallback
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_context, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done.
}
@Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
1. Create XML menu resource file and assign appearance and position attributes
2. Add ImageButton for the popup menu icon in the XML activity layout file
3. Assign onClickListener to ImageButton
4. Override onClick() to inflate the popup and register it with
onMenuItemClickListener()
5. Implement onMenuItemClick()
6. Create a method to perform an action for each popup menu item
This work is licensed under a Creative
Menus and
Android Developer Fundamentals Commons Attribution 4.0 International 82
pickers License.
V2
Add ImageButton
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button_popup"
android:src="@drawable/@drawable/ic_action_popup"/>
In onCreate():
mButton.setOnClickListener(new View.OnClickListener() {
// define onClick
});
@Override
public void onBackPressed() {
// Add the Back key handler here.
return;
}
Descendant navigation
1. Icon in app bar
2. Header
3. Menu items
<activity android:name=".OrderActivity"
android:label="@string/title_activity_order"
android:parentActivityName="com.example.android.
optionsmenuorderactivity.MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="@id/tab_layout" />
dependencies {
...
compile 'com.android.support:recyclerview-v7:26.1.0'
...
}
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
● onCreateViewHolder()
● inBindViewHolder()
● getItemCount()
@Override
public int getItemCount() {
// Return the number of data items to display
return mWordList.size();
}
mRecyclerView = findViewById(R.id.recyclerview);
mAdapter = new WordListAdapter(this, mWordList);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new
LinearLayoutManager(this));
● Drawables
● Creating image assets
● Styles
● Themes
Text
3. Click icon to chose clipart
4. Inspect assets for 4
<resources>
<style name="CodeFont">
<item name="android:textColor">#00FF00</item>
<item name="android:typeface">monospace</item>
</style>
</resources>
<resources>
<style name="RedCode" parent="@style/Codefont>
<item name="android:textColor">#FF0000</item>
</style>
</resources>
● Android Styles
● Android Themes
● Styles and Themes Guide
● DayNight Theme Guide
● Threads
● AsyncTask
● Loaders
● AsyncTaskLoader
● AsyncTask
● The Loader Framework
● Services
Worker Thread Do some work
AsyncTask and This work is licensed under a Creative
Android Developer Fundamentals Commons Attribution 4.0 International 196
AsyncTaskLoader
V2 License.
Two rules for Android threads
Worker Thread
doInBackground()
● onProgressUpdate()
○ Runs on the main thread
○ receives calls from publishProgress() from background thread
doInBackground()
doInBackground()
doInBackground()
onProgressUpdate()
doInBackground(
onPostExecute()
● String—could be query, URI for filename
● Integer—percentage completed, steps done
● Bitmap—an image to be displayed
● Use Void if no data passed
AsyncTask and This work is licensed under a Creative
Android Developer Fundamentals Commons Attribution 4.0 International 204
AsyncTaskLoader
V2 License.
onPreExecute()
LoaderManager
Request Receive
Work Result
Activity
AsyncTask and This work is licensed under a Creative
Android Developer Fundamentals Commons Attribution 4.0 International 218
AsyncTaskLoader
V2 License.
AsyncTask AsyncTaskLoader
doInBackground() loadInBackground()
onPostExecute() onLoadFinished()
1. Subclass AsyncTaskLoader
2. Implement constructor
3. loadInBackground()
4. onStartLoading()
@Override
public Loader<List<String>> onCreateLoader(int id, Bundle args) {
return new StringListLoader(this,args.getString("queryString"));
}
@Override
public void onLoaderReset(final LoaderList<String>> loader) { }
● Broadcasts
● Send a custom broadcasts
● Broadcast receivers
● Implementing broadcast receivers
● Restricting the broadcasts
● Best practices
Types of broadcast:
● System broadcast.
● Custom broadcast.
Few examples:
● An Intent with action, ACTION_BOOT_COMPLETED is broadcasted
when the device boots.
● An Intent with action, ACTION_POWER_CONNECTED is broadcasted
when the device is connected to the external power.
Custom broadcasts are broadcasts that your app sends out, similar to the
Android system.
For example, when you want to let other app(s) know that some data has
been downloaded by your app, and its available for their use.
LocalBroadcastManager.getInstance(this)
.sendBroadcast(customBroadcastIntent);
This work is licensed under a Creative
Android Developer Fundamentals Broadcasts Commons Attribution 4.0 International 240
V2 License.
Broadcast
Receivers
To add an intent-filter:
● To your AndroidManifest.xml file, use <intent-
filter> tag.
● To your Java file use the IntentFilter object.
This work is licensed under a Creative
Android Developer Fundamentals Broadcasts Commons Attribution 4.0 International 248
V2 License.
Subclass a broadcast receiver
LocalBroadcastManager.getInstance(this).registerReceiver
(mReceiver,
new IntentFilter(CustomReceiver.ACTION_CUSTOM_BROADCAST));
LocalBroadcastManager.getInstance(this)
.unregisterReceiver(mReceiver);
● Network transactions.
● Play music.
● Perform file I/O.
● Interact with a database.
Although services are separate from the UI, they still run
on the main thread by default (except IntentService)
If the service can't access the UI, how do you update the app
to show the results?
@Override
protected void onHandleIntent(Intent intent) {
try {
// Do some work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} // When this method returns, IntentService stops the service, as appropriate.
}
■ Small icon
■ Title
■ Detail text
setPriority(NotificationCompat.PRIORITY_HIGH)
This work is licensed under a Creative
Android Developer Fundamentals Notifications Commons Attribution 4.0 International 296
V2 License.
Importance level and priority
constants
User-visible importance level
Importance (Android Priority (Android 7.1
8.0 and higher) and lower)
Urgent
PRIORITY_HIGH or
Makes a sound and appears as a heads-up IMPORTANCE_HIGH
PRIORITY_MAX
notification
High IMPORTANCE_DEFAU PRIORITY_DEFAUL
Makes a sound LT T
Medium
IMPORTANCE_LOW PRIORITY_LOW
No sound
Low
No sound and doesn't appear in the status bar IMPORTANCE_MIN PRIORITY_MIN
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.android_icon)
.setContentTitle("You've been notified!")
.setContentText("This is your notification text.");
1. Application context
2. Request code—constant integer id for the pending intent
3. Intent to be delivered
4. PendingIntent flag determines how the system handles
multiple pending intents from same app
Intent notificationIntent =
new Intent(this, MainActivity.class);
PendingIntent notificationPendingIntent =
PendingIntent.getActivity(
this,
NOTIFICATION_ID,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
.setContentIntent(notificationPendingIntent);
.addAction(R.drawable.ic_color_lens_black_24dp,
"R.string.label",
notificationPendingIntent);
NotificationCompa.BigPictureStyle
mNotifyManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
mNotifyManager.notify(NOTIFICATION_ID, myNotification);
mNotifyManager.cancel(NOTIFICATION_ID);
This work is licensed under a Creative
Android Developer Fundamentals Notifications Commons Attribution 4.0 International 324
V2 License.
Design guidelines
If your app sends too many notifications, users will disable
notifications or uninstall the app.
● Relevant: Whether this information is essential for the user.
● Timely: Notifications need to appear when they are useful.
● Short: Use as few words as possible.
● Give users the power to choose -- Use appropriate
notification channels to categorise your notifications.
This work is licensed under a Creative
Android Developer Fundamentals Notifications Commons Attribution 4.0 International 325
V2 License.