SlideShare una empresa de Scribd logo
1 de 33
Descargar para leer sin conexión
Android Support Library:
Using ActionBarCompat
Christophe Beyls
DevFest Belgium 2013
About the speaker
● Mobile developer living in Brussels.
● Regular attendee of GTUG
and Café Numerique.
● Developed Brussels Transports for Android
during my spare time.

@BladeCoder
plus.google.com/+ChristopheBeyls
Agenda
● Introduction to the support library
● ActionBarCompat vs
ActionBarSherlock
● Setup & detailed usage
● Limitations & workarounds
● Migrating from ActionBarSherlock to
ActionBarCompat
● Bugs & fixes
The Android Support Library - Features
Mandatory library for (almost) any kind of
Android project.
● Brings Fragments and Loaders to Android
1.6+
● Utility classes to use newer Android
features only if available
○ TaskStackBuilder, NavUtils (navigation)
○ NotificationCompat
○ ShareCompat
The Android Support Library - Features
● General utility classes
○
○
○
○

LocalBroadcastManager (message bus)
LruCache (backport)
LongSparseArray (backport)
WakefulBroadcastReceiver

● New UI widgets

○ ViewPager (+ PagerTabStrip, PagerTitleStrip)
○ SlidingPaneLayout
○ DrawerLayout
ActionBarCompat

http://developer.android.com/guide/topics/ui/actionbar.html

● Introduced in may 2013 as part of the
Android support library v18
● Requires & extends android-support-v4.jar
● Provides ActionBar support for Android 2.1+
(API 7+)
● Mimics the native ActionBar API
ActionBarCompat vs
ActionBarSherlock
Roughly similar to ActionBarSherlock, but:
● Supported & used by Google
● Makes your code cleaner with less
dependencies
● Produces a slightly smaller apk file
● Fully supports ActionBarDrawerToggle
ActionBarCompat vs
ActionBarSherlock
● Android 4+ styled overflow menu
Behaviour
ActionBarCompat works in two different
modes depending on the Android version.
● Android 2.1 to 3.2
A compatibility ActionBar will be used.
It is drawn inside the main content view.
● Android 4+
The native ActionBar will be used.
Method calls will be routed to the native
implementation.
Project Setup
Update Android Support Library to the latest version.
● Eclipse
Import library project from local folder:
[sdk]/extras/android/support/v7/appcompat
/android-support-v7-appcompat

● Android Studio
Add dependency to build.gradle:
dependencies {
compile "com.android.support:appcompat-v7:18.0.+"
...
}
Usage - Styles
First, make your app styles inherit from
ActionBarCompat styles.
/res/values/styles.xml
<style name="AppTheme" parent="@style/Theme.AppCompat">
...
</style>

● Theme.AppCompat
● Theme.AppCompat.Light
● Theme.AppCompat.Light.DarkActionBar
Usage - Styles
To customize the ActionBar appearance,
double-set each attribute in the theme.
<style name="AppTheme" parent="@style/Theme.AppCompat">
<item name="android:actionBarStyle">
@style/myapp_ActionBar</item>
<item name="actionBarStyle">@style/myapp_ActionBar</item>
</style>
<style name="myapp_ActionBar"
parent="@style/Widget.AppCompat.ActionBar">
<item name="android:background">
@drawable/custom_background</item>
<item name="background">@drawable/custom_background</item>
</style>
Usage - ActionBarActivity
Make your Activities inherit from
ActionBarActivity and use the support methods.
public class MyActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
bar.setTitle("Hello DevFest!");
...
}
}
Usage - ActionBarActivity
ActionBar-related support methods
● getSupportActionBar()
● supportInvalidateOptionsMenu()
● supportRequestWindowFeature() [not in ABS]
● setSupportProgress()
● setSupportProgressBarIndeterminateVisibility()
● startSupportActionMode()
Never call the corresponding native methods
if you use ActionBarCompat!
Always call these methods after super.onCreate()
Usage - ActionBarActivity
Example - Showing a Progress Bar
public class ProgressActivity extends ActionBarActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.content);
ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
bar.setTitle("Hello DevFest!");
...
}
private void startLoading() {
setSupportProgressBarIndeterminateVisibility(true);
getSupportLoaderManager().initLoader(MY_LOADER_ID, null, myLoaderCallbacks);
}
}
Usage - ActionBarActivity
Single Fragment container
Typical code
public class SingleFragmentActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
bar.setTitle("Hello DevFest!");
if (savedInstanceState == null) {
MyFragment f = MyFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, f).commit();
}
}
}

➔ Will not work with ActionBarCompat.
Usage - ActionBarActivity
Single Fragment container
Universal code
public class SingleFragmentActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
bar.setTitle("Hello DevFest!");
if (savedInstanceState == null) {
MyFragment f = MyFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.add(R.id.app_content, f).commit();
}
}
}
Usage - ActionBarActivity
Single Fragment container
Universal code
/res/layout/content.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/app_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />

or just insert the fragment directly in your layout:
<fragment android:name="com.example.myapp.MyFragment"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Usage - Fragments
Just inherit from the standard Fragment class
of the Support Library.
Usage - Menus
1. Define menus in resources as usual, but use the
app local namespace for Android 3+ attributes.
/res/menu/refresh.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<item
android:id="@+id/refresh"
android:icon="@drawable/action_refresh"
android:title="@string/refresh"
app:showAsAction="ifRoom"/>
</menu>
Usage - Menus
Android 3+ menu items attributes:
● showAsAction
● actionLayout
● actionViewClass
● actionProviderClass
Usage - Menus
2. Use static methods in MenuItemCompat for
Android 3+ MenuItem methods.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.realtime, menu);
boolean hasInfoMessage = !TextUtils.isEmpty(message);
menu.findItem(R.id.info_message).setVisible(hasInfoMessage)
.setEnabled(hasInfoMessage);
MenuItemCompat.setActionProvider(menu.findItem(R.id.share),
new ShareActionProvider(getActivity()));
}
Usage - Menus
Android 3+ MenuItem methods:
● setActionProvider()
● getActionProvider()
● setActionView()
● getActionView()
● expandActionView()
● collapseActionView()
● isActionViewExpanded()
● setOnActionExpandListener()
● setShowAsAction()
Migrating from ActionBarSherlock
to ActionBarCompat
In 7 steps
1. Styles resources
Theme.Sherlock.* ➔ Theme.AppCompat.*
Widget.Sherlock.* ➔ Widget.AppCompat.*
2. SherlockActivity ➔ ActionBarActivity
3. Sherlock*Fragment ➔ *Fragment
4. requestWindowFeature() ➔
supportRequestWindowFeature()
and move the call after super.onCreate()
Migrating from ActionBarSherlock
to ActionBarCompat
5. Remove references to the top-level android.
R.id.content and use a custom top
container layout instead.
6. Menu resources
Replace the android: namespace with the
app local namespace for Android 3+ attributes.
7. Menu items code
Replace the ActionBarSherlock MenuItems
with the native MenuItems
+ MenuItemCompat static methods, if needed.
Styling Bugs - Issue 58498
1. Too small tabs (on older devices)
Styling Bugs
1. Too small tabs - fix
/res/values/styles.xml
<style name="AppTheme" parent="@style/Theme.AppCompat">
...
<item name="android:actionBarTabStyle">
@style/myapp_ActionBarTabStyle</item>
<item name="actionBarTabStyle">@style/myapp_ActionBarTabStyle</item>
</style>
<style name="myapp_ActionBarTabStyle"
parent="@style/Widget.AppCompat.ActionBar.TabView">
...
<!-- AppCompat fix for the compatibility ActionBar -->
<item name="android:minWidth">107dp</item>
</style>
Styling Bugs
2. Landscape glitches (on older devices)
Styling Bugs
2. Landscape glitches (on older devices)
Styling Bugs
2. Landscape glitches - fix
/res/values/styles.xml
<style name="AppTheme" parent="@style/Theme.AppCompat">
...
<item name="android:actionBarStyle">
@style/myapp_transparent_ActionBar</item>
<item name="actionBarStyle">@style/myapp_ActionBar</item>
</style>
<style name="myapp_ActionBar" parent="@style/Widget.AppCompat.ActionBar">
...
<!-- AppCompat fixes for the compatibility ActionBar -->
<item name="indeterminateProgressStyle">
@android:style/Widget.ProgressBar.Small</item>
</style>
One more thing…
Missing feature
No support for preference screens ?
➔ PreferenceActivity is mandatory to support
preference screens on older devices.
➔ There is no ActionBarPreferenceActivity, so:
◆ Either you get no ActionBar at all on the preferences
screen
◆ Or you create two preference activities and use a
native ActionBar on newer devices.
◆ You need to override the styles.
Missing feature
Alternative: use a custom PreferenceFragment
● I created a simple PreferenceFragment for
the support library.
● Based on the platform’s
PreferenceFragment with some reflection to
access a few protected methods.
● Works with ActionBarActivity.
● Source code can be found here:
https://gist.github.com/cbeyls
The End

Thanks for watching!

@BladeCoder - plus.google.com/+ChristopheBeyls

Más contenido relacionado

La actualidad más candente

Classing up ES6 - Web Directions code 2015 (1)
Classing up ES6 - Web Directions code 2015 (1)Classing up ES6 - Web Directions code 2015 (1)
Classing up ES6 - Web Directions code 2015 (1)
Andy Sharman
 
Курсы по мобильной разработке под iOS. 4 лекция. Возможности телефона
Курсы по мобильной разработке под iOS. 4 лекция. Возможности телефонаКурсы по мобильной разработке под iOS. 4 лекция. Возможности телефона
Курсы по мобильной разработке под iOS. 4 лекция. Возможности телефона
Глеб Тарасов
 

La actualidad más candente (20)

Dojo Confessions
Dojo ConfessionsDojo Confessions
Dojo Confessions
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Gutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisablesGutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisables
 
Classing up ES6 - Web Directions code 2015 (1)
Classing up ES6 - Web Directions code 2015 (1)Classing up ES6 - Web Directions code 2015 (1)
Classing up ES6 - Web Directions code 2015 (1)
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Jquery Fundamentals
Jquery FundamentalsJquery Fundamentals
Jquery Fundamentals
 
안드로이드 데이터 바인딩
안드로이드 데이터 바인딩안드로이드 데이터 바인딩
안드로이드 데이터 바인딩
 
Beyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS AppsBeyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS Apps
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code Organization
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
3D Touch: Preparando sua app para o futuro do iOS
3D Touch: Preparando sua app para o futuro do iOS3D Touch: Preparando sua app para o futuro do iOS
3D Touch: Preparando sua app para o futuro do iOS
 
Using Objects to Organize your jQuery Code
Using Objects to Organize your jQuery CodeUsing Objects to Organize your jQuery Code
Using Objects to Organize your jQuery Code
 
Javascript is your (Auto)mate
Javascript is your (Auto)mateJavascript is your (Auto)mate
Javascript is your (Auto)mate
 
BVJS
BVJSBVJS
BVJS
 
Курсы по мобильной разработке под iOS. 4 лекция. Возможности телефона
Курсы по мобильной разработке под iOS. 4 лекция. Возможности телефонаКурсы по мобильной разработке под iOS. 4 лекция. Возможности телефона
Курсы по мобильной разработке под iOS. 4 лекция. Возможности телефона
 
Optimize CollectionView Scrolling
Optimize CollectionView ScrollingOptimize CollectionView Scrolling
Optimize CollectionView Scrolling
 
Backbone js
Backbone jsBackbone js
Backbone js
 
【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップ
【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップ【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップ
【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップ
 
Yui3在美团
Yui3在美团Yui3在美团
Yui3在美团
 
Android mix Java and C++
Android mix Java and C++Android mix Java and C++
Android mix Java and C++
 

Destacado

Agama tokoh istiqomah
Agama tokoh istiqomahAgama tokoh istiqomah
Agama tokoh istiqomah
Anissa Nazda
 
Beyond company profile feb 2013 eng
Beyond company profile  feb 2013 engBeyond company profile  feb 2013 eng
Beyond company profile feb 2013 eng
Husna1965
 
Gestion basica de la informacion
Gestion basica de la informacionGestion basica de la informacion
Gestion basica de la informacion
UNIMINUTO
 
краткая биография всемирно известных актеров великобритании
краткая биография всемирно известных актеров великобританиикраткая биография всемирно известных актеров великобритании
краткая биография всемирно известных актеров великобритании
Алексей Галахов
 
Gbi 130219083032-phpapp02
Gbi 130219083032-phpapp02Gbi 130219083032-phpapp02
Gbi 130219083032-phpapp02
kurt6008
 
Introduction to Android (Jeudis du libre)
Introduction to Android (Jeudis du libre)Introduction to Android (Jeudis du libre)
Introduction to Android (Jeudis du libre)
cbeyls
 
Reflection Resource from the 2013 National Service Learning Conference
Reflection Resource from the 2013 National Service Learning ConferenceReflection Resource from the 2013 National Service Learning Conference
Reflection Resource from the 2013 National Service Learning Conference
Clement Coulston
 
Adaptive missile-guidance-using-gps
Adaptive missile-guidance-using-gpsAdaptive missile-guidance-using-gps
Adaptive missile-guidance-using-gps
Vinod Kumar
 

Destacado (18)

Agama tokoh istiqomah
Agama tokoh istiqomahAgama tokoh istiqomah
Agama tokoh istiqomah
 
Professional Development Opportunity on Google Drive
Professional Development Opportunity on Google DriveProfessional Development Opportunity on Google Drive
Professional Development Opportunity on Google Drive
 
Global business
Global businessGlobal business
Global business
 
Beyond company profile feb 2013 eng
Beyond company profile  feb 2013 engBeyond company profile  feb 2013 eng
Beyond company profile feb 2013 eng
 
Gestion basica de la informacion
Gestion basica de la informacionGestion basica de la informacion
Gestion basica de la informacion
 
Bai tap lon xac xuat thong ke
Bai tap lon xac xuat thong keBai tap lon xac xuat thong ke
Bai tap lon xac xuat thong ke
 
краткая биография всемирно известных актеров великобритании
краткая биография всемирно известных актеров великобританиикраткая биография всемирно известных актеров великобритании
краткая биография всемирно известных актеров великобритании
 
Search Tips
Search TipsSearch Tips
Search Tips
 
Anisa wahyuni
Anisa wahyuniAnisa wahyuni
Anisa wahyuni
 
Gbi 130219083032-phpapp02
Gbi 130219083032-phpapp02Gbi 130219083032-phpapp02
Gbi 130219083032-phpapp02
 
Introduction to Android (Jeudis du libre)
Introduction to Android (Jeudis du libre)Introduction to Android (Jeudis du libre)
Introduction to Android (Jeudis du libre)
 
You can sell presentation
You can sell presentationYou can sell presentation
You can sell presentation
 
gerak melingkar dengan laju konstan
gerak melingkar dengan laju konstangerak melingkar dengan laju konstan
gerak melingkar dengan laju konstan
 
Reflection Resource from the 2013 National Service Learning Conference
Reflection Resource from the 2013 National Service Learning ConferenceReflection Resource from the 2013 National Service Learning Conference
Reflection Resource from the 2013 National Service Learning Conference
 
Perfetti’s distribution
Perfetti’s distributionPerfetti’s distribution
Perfetti’s distribution
 
Buzz marketing by sandip
Buzz marketing by sandipBuzz marketing by sandip
Buzz marketing by sandip
 
Routing
RoutingRouting
Routing
 
Adaptive missile-guidance-using-gps
Adaptive missile-guidance-using-gpsAdaptive missile-guidance-using-gps
Adaptive missile-guidance-using-gps
 

Similar a Android Support Library: Using ActionBarCompat

Android App Development 03 : Widget &amp; UI
Android App Development 03 : Widget &amp; UIAndroid App Development 03 : Widget &amp; UI
Android App Development 03 : Widget &amp; UI
Anuchit Chalothorn
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
Yekmer Simsek
 

Similar a Android Support Library: Using ActionBarCompat (20)

Testing android apps with espresso
Testing android apps with espressoTesting android apps with espresso
Testing android apps with espresso
 
Android App Development - 05 Action bar
Android App Development - 05 Action barAndroid App Development - 05 Action bar
Android App Development - 05 Action bar
 
Android App Development 03 : Widget &amp; UI
Android App Development 03 : Widget &amp; UIAndroid App Development 03 : Widget &amp; UI
Android App Development 03 : Widget &amp; UI
 
Android 3
Android 3Android 3
Android 3
 
Lesson 9
Lesson 9Lesson 9
Lesson 9
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
 
Android Workshop 2013
Android Workshop 2013Android Workshop 2013
Android Workshop 2013
 
Google I/O 2019 - what's new in Android Q and Jetpack
Google I/O 2019 - what's new in Android Q and JetpackGoogle I/O 2019 - what's new in Android Q and Jetpack
Google I/O 2019 - what's new in Android Q and Jetpack
 
Fragment
Fragment Fragment
Fragment
 
Introduction to Honeycomb APIs - Android Developer Lab 2011 Q3
Introduction to Honeycomb APIs - Android Developer Lab 2011 Q3Introduction to Honeycomb APIs - Android Developer Lab 2011 Q3
Introduction to Honeycomb APIs - Android Developer Lab 2011 Q3
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
Android design patterns
Android design patternsAndroid design patterns
Android design patterns
 
EP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For AssetsEP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
 
Material Design and Backwards Compatibility
Material Design and Backwards CompatibilityMaterial Design and Backwards Compatibility
Material Design and Backwards Compatibility
 
Android Lollipop - Webinar am 11.12.2014
Android Lollipop - Webinar am 11.12.2014Android Lollipop - Webinar am 11.12.2014
Android Lollipop - Webinar am 11.12.2014
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
The Action Bar: Front to Back
The Action Bar: Front to BackThe Action Bar: Front to Back
The Action Bar: Front to Back
 
MVP Community Camp 2014 - How to use enhanced features of Windows 8.1 Store ...
MVP Community Camp 2014 - How to useenhanced features of Windows 8.1 Store ...MVP Community Camp 2014 - How to useenhanced features of Windows 8.1 Store ...
MVP Community Camp 2014 - How to use enhanced features of Windows 8.1 Store ...
 
Top Tips for Android UIs - Getting the Magic on Tablets
Top Tips for Android UIs - Getting the Magic on TabletsTop Tips for Android UIs - Getting the Magic on Tablets
Top Tips for Android UIs - Getting the Magic on Tablets
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

Android Support Library: Using ActionBarCompat

  • 1. Android Support Library: Using ActionBarCompat Christophe Beyls DevFest Belgium 2013
  • 2. About the speaker ● Mobile developer living in Brussels. ● Regular attendee of GTUG and Café Numerique. ● Developed Brussels Transports for Android during my spare time. @BladeCoder plus.google.com/+ChristopheBeyls
  • 3. Agenda ● Introduction to the support library ● ActionBarCompat vs ActionBarSherlock ● Setup & detailed usage ● Limitations & workarounds ● Migrating from ActionBarSherlock to ActionBarCompat ● Bugs & fixes
  • 4. The Android Support Library - Features Mandatory library for (almost) any kind of Android project. ● Brings Fragments and Loaders to Android 1.6+ ● Utility classes to use newer Android features only if available ○ TaskStackBuilder, NavUtils (navigation) ○ NotificationCompat ○ ShareCompat
  • 5. The Android Support Library - Features ● General utility classes ○ ○ ○ ○ LocalBroadcastManager (message bus) LruCache (backport) LongSparseArray (backport) WakefulBroadcastReceiver ● New UI widgets ○ ViewPager (+ PagerTabStrip, PagerTitleStrip) ○ SlidingPaneLayout ○ DrawerLayout
  • 6. ActionBarCompat http://developer.android.com/guide/topics/ui/actionbar.html ● Introduced in may 2013 as part of the Android support library v18 ● Requires & extends android-support-v4.jar ● Provides ActionBar support for Android 2.1+ (API 7+) ● Mimics the native ActionBar API
  • 7. ActionBarCompat vs ActionBarSherlock Roughly similar to ActionBarSherlock, but: ● Supported & used by Google ● Makes your code cleaner with less dependencies ● Produces a slightly smaller apk file ● Fully supports ActionBarDrawerToggle
  • 9. Behaviour ActionBarCompat works in two different modes depending on the Android version. ● Android 2.1 to 3.2 A compatibility ActionBar will be used. It is drawn inside the main content view. ● Android 4+ The native ActionBar will be used. Method calls will be routed to the native implementation.
  • 10. Project Setup Update Android Support Library to the latest version. ● Eclipse Import library project from local folder: [sdk]/extras/android/support/v7/appcompat /android-support-v7-appcompat ● Android Studio Add dependency to build.gradle: dependencies { compile "com.android.support:appcompat-v7:18.0.+" ... }
  • 11. Usage - Styles First, make your app styles inherit from ActionBarCompat styles. /res/values/styles.xml <style name="AppTheme" parent="@style/Theme.AppCompat"> ... </style> ● Theme.AppCompat ● Theme.AppCompat.Light ● Theme.AppCompat.Light.DarkActionBar
  • 12. Usage - Styles To customize the ActionBar appearance, double-set each attribute in the theme. <style name="AppTheme" parent="@style/Theme.AppCompat"> <item name="android:actionBarStyle"> @style/myapp_ActionBar</item> <item name="actionBarStyle">@style/myapp_ActionBar</item> </style> <style name="myapp_ActionBar" parent="@style/Widget.AppCompat.ActionBar"> <item name="android:background"> @drawable/custom_background</item> <item name="background">@drawable/custom_background</item> </style>
  • 13. Usage - ActionBarActivity Make your Activities inherit from ActionBarActivity and use the support methods. public class MyActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content); ActionBar bar = getSupportActionBar(); bar.setDisplayHomeAsUpEnabled(true); bar.setTitle("Hello DevFest!"); ... } }
  • 14. Usage - ActionBarActivity ActionBar-related support methods ● getSupportActionBar() ● supportInvalidateOptionsMenu() ● supportRequestWindowFeature() [not in ABS] ● setSupportProgress() ● setSupportProgressBarIndeterminateVisibility() ● startSupportActionMode() Never call the corresponding native methods if you use ActionBarCompat! Always call these methods after super.onCreate()
  • 15. Usage - ActionBarActivity Example - Showing a Progress Bar public class ProgressActivity extends ActionBarActivity { ... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.content); ActionBar bar = getSupportActionBar(); bar.setDisplayHomeAsUpEnabled(true); bar.setTitle("Hello DevFest!"); ... } private void startLoading() { setSupportProgressBarIndeterminateVisibility(true); getSupportLoaderManager().initLoader(MY_LOADER_ID, null, myLoaderCallbacks); } }
  • 16. Usage - ActionBarActivity Single Fragment container Typical code public class SingleFragmentActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar bar = getSupportActionBar(); bar.setDisplayHomeAsUpEnabled(true); bar.setTitle("Hello DevFest!"); if (savedInstanceState == null) { MyFragment f = MyFragment.newInstance(); getSupportFragmentManager().beginTransaction() .add(android.R.id.content, f).commit(); } } } ➔ Will not work with ActionBarCompat.
  • 17. Usage - ActionBarActivity Single Fragment container Universal code public class SingleFragmentActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content); ActionBar bar = getSupportActionBar(); bar.setDisplayHomeAsUpEnabled(true); bar.setTitle("Hello DevFest!"); if (savedInstanceState == null) { MyFragment f = MyFragment.newInstance(); getSupportFragmentManager().beginTransaction() .add(R.id.app_content, f).commit(); } } }
  • 18. Usage - ActionBarActivity Single Fragment container Universal code /res/layout/content.xml <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/app_content" android:layout_width="match_parent" android:layout_height="match_parent" /> or just insert the fragment directly in your layout: <fragment android:name="com.example.myapp.MyFragment" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" />
  • 19. Usage - Fragments Just inherit from the standard Fragment class of the Support Library.
  • 20. Usage - Menus 1. Define menus in resources as usual, but use the app local namespace for Android 3+ attributes. /res/menu/refresh.xml <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" > <item android:id="@+id/refresh" android:icon="@drawable/action_refresh" android:title="@string/refresh" app:showAsAction="ifRoom"/> </menu>
  • 21. Usage - Menus Android 3+ menu items attributes: ● showAsAction ● actionLayout ● actionViewClass ● actionProviderClass
  • 22. Usage - Menus 2. Use static methods in MenuItemCompat for Android 3+ MenuItem methods. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.realtime, menu); boolean hasInfoMessage = !TextUtils.isEmpty(message); menu.findItem(R.id.info_message).setVisible(hasInfoMessage) .setEnabled(hasInfoMessage); MenuItemCompat.setActionProvider(menu.findItem(R.id.share), new ShareActionProvider(getActivity())); }
  • 23. Usage - Menus Android 3+ MenuItem methods: ● setActionProvider() ● getActionProvider() ● setActionView() ● getActionView() ● expandActionView() ● collapseActionView() ● isActionViewExpanded() ● setOnActionExpandListener() ● setShowAsAction()
  • 24. Migrating from ActionBarSherlock to ActionBarCompat In 7 steps 1. Styles resources Theme.Sherlock.* ➔ Theme.AppCompat.* Widget.Sherlock.* ➔ Widget.AppCompat.* 2. SherlockActivity ➔ ActionBarActivity 3. Sherlock*Fragment ➔ *Fragment 4. requestWindowFeature() ➔ supportRequestWindowFeature() and move the call after super.onCreate()
  • 25. Migrating from ActionBarSherlock to ActionBarCompat 5. Remove references to the top-level android. R.id.content and use a custom top container layout instead. 6. Menu resources Replace the android: namespace with the app local namespace for Android 3+ attributes. 7. Menu items code Replace the ActionBarSherlock MenuItems with the native MenuItems + MenuItemCompat static methods, if needed.
  • 26. Styling Bugs - Issue 58498 1. Too small tabs (on older devices)
  • 27. Styling Bugs 1. Too small tabs - fix /res/values/styles.xml <style name="AppTheme" parent="@style/Theme.AppCompat"> ... <item name="android:actionBarTabStyle"> @style/myapp_ActionBarTabStyle</item> <item name="actionBarTabStyle">@style/myapp_ActionBarTabStyle</item> </style> <style name="myapp_ActionBarTabStyle" parent="@style/Widget.AppCompat.ActionBar.TabView"> ... <!-- AppCompat fix for the compatibility ActionBar --> <item name="android:minWidth">107dp</item> </style>
  • 28. Styling Bugs 2. Landscape glitches (on older devices)
  • 29. Styling Bugs 2. Landscape glitches (on older devices)
  • 30. Styling Bugs 2. Landscape glitches - fix /res/values/styles.xml <style name="AppTheme" parent="@style/Theme.AppCompat"> ... <item name="android:actionBarStyle"> @style/myapp_transparent_ActionBar</item> <item name="actionBarStyle">@style/myapp_ActionBar</item> </style> <style name="myapp_ActionBar" parent="@style/Widget.AppCompat.ActionBar"> ... <!-- AppCompat fixes for the compatibility ActionBar --> <item name="indeterminateProgressStyle"> @android:style/Widget.ProgressBar.Small</item> </style>
  • 31. One more thing… Missing feature No support for preference screens ? ➔ PreferenceActivity is mandatory to support preference screens on older devices. ➔ There is no ActionBarPreferenceActivity, so: ◆ Either you get no ActionBar at all on the preferences screen ◆ Or you create two preference activities and use a native ActionBar on newer devices. ◆ You need to override the styles.
  • 32. Missing feature Alternative: use a custom PreferenceFragment ● I created a simple PreferenceFragment for the support library. ● Based on the platform’s PreferenceFragment with some reflection to access a few protected methods. ● Works with ActionBarActivity. ● Source code can be found here: https://gist.github.com/cbeyls
  • 33. The End Thanks for watching! @BladeCoder - plus.google.com/+ChristopheBeyls