<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>AppCompat Archives - Truiton</title>
	<atom:link href="https://www.truiton.com/tag/appcompat/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>Technology Reaching Us In Time - Online</description>
	<lastBuildDate>Wed, 25 Sep 2019 11:42:18 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/11/cropped-truiton_new_logo_half_white.png?fit=32%2C32&#038;ssl=1</url>
	<title>AppCompat Archives - Truiton</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">54534495</site>	<item>
		<title>Android Action Bar In A Dialog Using ToolBar</title>
		<link>https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/</link>
					<comments>https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/#comments</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Sat, 25 Apr 2015 16:43:38 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[AppCompat]]></category>
		<category><![CDATA[Toolbar]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://www.truiton.com/?p=1209</guid>

					<description><![CDATA[<p>Android Toolbar widget is one of the new UI components available in AppCompat v21. This widget works just like an ActionBar, the only difference is, it can be placed any where on screen. The Android Toolbar widget can also be used to replace the original ActionBar in your Activity. This feature will open many new&#8230;&#160;<a href="https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Android Action Bar In A Dialog Using ToolBar</span></a></p>
<p>The post <a href="https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/">Android Action Bar In A Dialog Using ToolBar</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" fetchpriority="high" decoding="async" width="950" height="534" data-attachment-id="1210" data-permalink="https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/android-action-bar-in-a-dialog/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Action-Bar-In-A-Dialog.jpg?fit=950%2C534&amp;ssl=1" data-orig-size="950,534" data-comments-opened="1" data-image-title="Android Action Bar In A Dialog" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Action-Bar-In-A-Dialog.jpg?fit=950%2C534&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Action-Bar-In-A-Dialog.jpg?resize=950%2C534" alt="Android Action Bar In A Dialog" class="wp-image-1210" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Action-Bar-In-A-Dialog.jpg?w=950&amp;ssl=1 950w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Action-Bar-In-A-Dialog.jpg?resize=600%2C337&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Action-Bar-In-A-Dialog.jpg?resize=300%2C169&amp;ssl=1 300w" sizes="(max-width: 950px) 100vw, 950px" /></figure></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Android Toolbar widget is one of the new UI components available in AppCompat v21. This widget works just like an ActionBar, the only difference is, it can be placed any where on screen. The Android <a href="https://developer.android.com/reference/android/support/v7/widget/Toolbar.html" target="_blank" rel="noopener noreferrer">Toolbar</a> widget can also be used to replace the original <a href="http://developer.android.com/reference/android/app/ActionBar.html" target="_blank" rel="noopener noreferrer">ActionBar</a> in your Activity. This feature will open many new possibilities in your application. Like you can place multiple action bars on a screen, place action bars / toolbars with some specific dimensions- not covering the whole width of the screen. Also it solves one of the major issue that I faced during development, i.e. placing an Android action bar in a dialog fragment. Now with Android&#8217;s ToolBar widget this can be done very easily.</p>



<p class="wp-block-paragraph">Android Toolbar widget supports a logo image, a title and a subtitle. It also supports a navigation button, custom views and more importantly an action menu. Now the question is how to display an action bar in a dialog using Toolbar widget.</p>



<h2 class="wp-block-heading">Android ActionBar in a DialogFragment</h2>



<p class="wp-block-paragraph">Android Toolbar is available through the AppCompat v21 support library. Therefore this widget can be used with Android API 7 and above without any problems. On the other hand DialogFragment class is already available in the support v4 library. Hence an Android ToolBar can be used to display the action bar in a dialog with support from API 7 onwards. To start off please make sure you have AppCompat dependencies in place:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">compile 'com.android.support:appcompat-v7:22.1.0'</pre>



<p class="wp-block-paragraph">Next you may need to include Android ToolBar in the dialog layout:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?xml version="1.0" encoding="utf-8"?>
&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    &lt;android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    &lt;TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/my_toolbar"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="50dp"
        android:layout_marginTop="50dp"/>

&lt;/RelativeLayout></pre>



<p class="wp-block-paragraph">As you can see in the highlighted lines above, I have used the <code>android.support.v7.widget.Toolbar</code> tag to display an action bar in the dialog&#8217;s layout. Android Toolbar widget can also be used with the styles defined in your app. As shown above, please use the <code>android:background</code> attribute to specify the color of action bar. Also <code>app:popupTheme</code> and <code>android:theme</code> attributes can be used to display the standard action bar themes as shown. Further lets define the DialogFragment class.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.toolbardialog;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

public class ActionBarDialog extends DialogFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Bundle args = getArguments();
        String title = args.getString("title");
        View v = inflater.inflate(R.layout.action_bar_dialog, container, false);
        TextView tv = (TextView) v.findViewById(R.id.text);
        tv.setText("This is an instance of ActionBarDialog");
        Toolbar toolbar = (Toolbar) v.findViewById(R.id.my_toolbar);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                // Handle the menu item
                return true;
            }
        });
        toolbar.inflateMenu(R.menu.menu_main);
        toolbar.setTitle(title);
        return v;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        // request a window without the title
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        return dialog;
    }
}
</pre>



<p class="wp-block-paragraph">As you can see in the above class, in <code>onCreateDialog</code> method I have applied, no title bar feature. This basically removes the header of <code>DialogFragment</code>. Now we can add our own header, a Toolbar which would act just like an Android ActionBar in the <code>DialogFragment</code>. I would also like to highlight that you can also receive arguments in this dialog from the calling activity by using <code>getArguments()</code> method, as shown above.</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" decoding="async" width="600" height="967" data-attachment-id="1213" data-permalink="https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/android-actionbar-dialog/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-ActionBar-Dialog.png?fit=600%2C967&amp;ssl=1" data-orig-size="600,967" data-comments-opened="1" data-image-title="Android ActionBar Dialog" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-ActionBar-Dialog.png?fit=600%2C967&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-ActionBar-Dialog.png?resize=600%2C967" alt="Android ActionBar Dialog" class="wp-image-1213" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-ActionBar-Dialog.png?w=600&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-ActionBar-Dialog.png?resize=186%2C300&amp;ssl=1 186w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-ActionBar-Dialog.png?resize=300%2C484&amp;ssl=1 300w" sizes="(max-width: 600px) 100vw, 600px" /></figure></div>



<h2 class="wp-block-heading">Using Android Toolbar instead of ActionBar</h2>



<p class="wp-block-paragraph">As I mentioned, the new Android Toolbar can also be used as a normal action bar in your fragment or activity. But to avoid conflict, first you may need to disable the standard action bar, by using a <code>Theme.AppCompat.NoActionBar</code> theme. Else you would see two action bars. In this example I have specified this theme in the styles.xml as only one activity was there. If you need to use Android ToolBar as an action bar for a specific activity, please use this theme only for that activity. Now lets have a look at styles.xml:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;resources>

    &lt;!-- Base application theme. -->
    &lt;style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        &lt;!-- Customize your theme here. -->
        &lt;!--   your app branding color for the app bar -->
        &lt;item name="colorPrimary">#3F51B5&lt;/item>
        &lt;!--   darker variant for the status bar and contextual app bars -->
        &lt;item name="colorPrimaryDark">#303F9F&lt;/item>
        &lt;!--   theme UI controls like checkboxes and text fields -->
        &lt;item name="colorAccent">#FF4081&lt;/item>
    &lt;/style>

&lt;/resources>
</pre>



<p class="wp-block-paragraph">Now that our activity will not be having an action bar, we need to define a Toolbar in the layout as shown:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".MainActivity">

    &lt;android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:elevation="8dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    &lt;ImageView
        android:id="@+id/logo"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:src="@mipmap/truiton_short_no_back"/>

    &lt;Button
        android:id="@+id/dialogButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Launch Dialog with Action Bar"/>

&lt;/RelativeLayout>
</pre>



<p class="wp-block-paragraph">Now lets have a look at the main activity:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.toolbardialog;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Button dialogButton = (Button) findViewById(R.id
                .dialogButton);
        dialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle args = new Bundle();
                args.putString("title", "Dialog with Action Bar");
                ActionBarDialog actionbarDialog = new ActionBarDialog();
                actionbarDialog.setArguments(args);
                actionbarDialog.show(getSupportFragmentManager(),
                        "action_bar_frag");
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
</pre>



<p class="wp-block-paragraph">As you can see in the above class, that I have used <code>setSupportActionBar(toolbar)</code> method to set the toolbar as default ActionBar. By doing this no extra code needs to be written for using the standard&nbsp;<code>onCreateOptionsMenu</code> and&nbsp;<code>onOptionsItemSelected</code> callback methods. Also please note: in <code>onClick</code> method, I am sending the arguments to <code>ActionBarDialog</code> class, where they are supposed to be used accordingly in the <code>DialogFragment</code>.</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" decoding="async" width="600" height="967" data-attachment-id="1214" data-permalink="https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/android-toolbar-example/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Toolbar-Example.png?fit=600%2C967&amp;ssl=1" data-orig-size="600,967" data-comments-opened="1" data-image-title="Android Toolbar Example" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Toolbar-Example.png?fit=600%2C967&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Toolbar-Example.png?resize=600%2C967" alt="Android Toolbar Example" class="wp-image-1214" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Toolbar-Example.png?w=600&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Toolbar-Example.png?resize=186%2C300&amp;ssl=1 186w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Toolbar-Example.png?resize=300%2C484&amp;ssl=1 300w" sizes="(max-width: 600px) 100vw, 600px" /></figure></div>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">To conclude I would say Android Toolbar widget is a great addition in the AppCompat class. This not only helps in showing an Android action bar in a dialog, but also helps us in many other ways. For example, when multiple action bars are required on a screen, or an action bar of variable width is required. Also Android Toolbar can be used in any layout, to display a fully functional ActionBar/Toolbar. Hope this helps. Connect with us on Facebook, Google+ and Twitter for more updates.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/">Android Action Bar In A Dialog Using ToolBar</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1209</post-id>	</item>
		<item>
		<title>Android SwitchCompat Example</title>
		<link>https://www.truiton.com/2015/03/android-switchcompat-example/</link>
					<comments>https://www.truiton.com/2015/03/android-switchcompat-example/#comments</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Sat, 07 Mar 2015 20:08:51 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Android SwitchCompat Example]]></category>
		<category><![CDATA[AppCompat]]></category>
		<guid isPermaLink="false">http://www.truiton.com/?p=911</guid>

					<description><![CDATA[<p>Being an Android developer I always had a development oriented approach. But once you start exploring things from a learning perspective, discoveries are stupendous. I never realized the full potential of AppCompat library in Android, I always thought; it just increases the size of my APK. Jokes apart, in recent turn of events I stumbled&#8230;&#160;<a href="https://www.truiton.com/2015/03/android-switchcompat-example/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Android SwitchCompat Example</span></a></p>
<p>The post <a href="https://www.truiton.com/2015/03/android-switchcompat-example/">Android SwitchCompat Example</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><a href="https://www.flickr.com/photos/peterthoeny/8919201291"><img data-recalc-dims="1" loading="lazy" decoding="async" width="640" height="464" data-attachment-id="912" data-permalink="https://www.truiton.com/2015/03/android-switchcompat-example/android-switch-button-example-featured/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Switch-Button-Example-Featured.jpg?fit=640%2C464&amp;ssl=1" data-orig-size="640,464" data-comments-opened="1" data-image-title="Android Switch Button Example &amp;#8211; Featured" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Switch-Button-Example-Featured.jpg?fit=640%2C464&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Switch-Button-Example-Featured.jpg?resize=640%2C464" alt="Photo Credit: Peter Thoeny - Android Switch Button Example" class="wp-image-912" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Switch-Button-Example-Featured.jpg?w=640&amp;ssl=1 640w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Switch-Button-Example-Featured.jpg?resize=300%2C218&amp;ssl=1 300w" sizes="auto, (max-width: 640px) 100vw, 640px" /></a></figure></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Being an Android developer I always had a development oriented approach. But once you start exploring things from a learning perspective, discoveries are stupendous. I never realized the full potential of AppCompat library in Android, I always thought; it just increases the size of my APK. Jokes apart, in recent turn of events I stumbled upon a situation where I wanted to use an android switch button in my app, where I should be able to drag that switch to an &#8220;On&#8221; or an &#8220;Off&#8221; state. To my dismay even this small task created problems. As a standard Android <a title="Android Switch" href="http://developer.android.com/reference/android/widget/Switch.html" target="_blank" rel="noopener noreferrer">switch</a> which supports the drag animations is only available from SDK v14 and above. I believe many of you must have faced this issue. This inspired me to write this Android switch button example.</p>



<p class="wp-block-paragraph">Recently in October 14, an update to AppCompat V7 was released, featuring version 21. This version majorly addressed the <a title="Android Material Design With Backward Compatibility" href="http://www.truiton.com/2015/02/android-material-design-backward-compatibility/" target="_blank" rel="noopener noreferrer">material design compatibility</a> issues. But a great feature that missed out the spotlight was the Android <a title="Android SwitchCompat Widget" href="https://developer.android.com/reference/android/support/v7/widget/SwitchCompat.html" target="_blank" rel="noopener noreferrer">SwitchCompat</a> widget. This Android switch button not only acts like a standard android switch which can be dragged by holding, but also works fine in Android API 7 and above if AppCompat v7 r21 is included in your project:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}</pre>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">In this example I would show how to make an Android switch button work in all Android API versions above 7.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Android SwitchCompat Example</h2>



<p class="wp-block-paragraph">In Android if you want to use a switch widget, which could be dragged into an &#8220;on&#8221; or &#8220;off&#8221; position with animation, you can use Android SwitchCompat widget. This widget can work perfectly with any Android 7+ SDK. It is supported through the AppCompat v7 library, which can be included in a project through gradle if you are using Android Studio or through a library project in Eclipse IDE. Lets have look at the Android SwitchCompat Example below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#FFFFFF"
                android:paddingBottom="@dimen/activity_vertical_margin"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                tools:context=".MainActivity">

    &lt;android.support.v7.widget.SwitchCompat
        android:id="@ id/switch_compat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="50dp"
        android:layout_marginStart="50dp"
        android:layout_marginTop="25dp"
        android:checked="false"
        android:text="SwitchCompat (SDK v7 )"
        android:textOff="OFF"
        android:textOn="ON"
        app:showText="true"/>

    &lt;android.support.v7.widget.SwitchCompat
        android:id="@ id/switch_compat2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@ id/switch_compat"
        android:layout_marginLeft="50dp"
        android:layout_marginStart="50dp"
        android:layout_marginTop="25dp"
        android:text="SwitchCompat (SDK v7 )"
        app:showText="false"/>

    &lt;ImageView
        android:id="@ id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@mipmap/truiton_short"/>

&lt;/RelativeLayout>
</pre>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Android SwitchCompat example screen would look like the screen shot below:</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="500" height="805" data-attachment-id="914" data-permalink="https://www.truiton.com/2015/03/android-switchcompat-example/android-switchcompat-example/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-SwitchCompat-Example.png?fit=500%2C805&amp;ssl=1" data-orig-size="500,805" data-comments-opened="1" data-image-title="Android SwitchCompat Example" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-SwitchCompat-Example.png?fit=500%2C805&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-SwitchCompat-Example.png?resize=500%2C805" alt="Android SwitchCompat Example" class="wp-image-914" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-SwitchCompat-Example.png?w=500&amp;ssl=1 500w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-SwitchCompat-Example.png?resize=186%2C300&amp;ssl=1 186w" sizes="auto, (max-width: 500px) 100vw, 500px" /></figure></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">An interesting feature in SwitchCompat button is that you can write text on its drawable thumb button. In the above XML I have shown two buttons, one with <code>app:showText="true"</code> and other without it. To use this property you may need to include <code>xmlns:app="http://schemas.android.com/apk/res-auto"</code> in the parent layout, as shown above. To make this Android switch button detect state change events you may need implement <a title="Android CompoundButton.OnCheckedChangeListener Interface" href="http://developer.android.com/reference/android/widget/CompoundButton.OnCheckedChangeListener.html" target="_blank" rel="noopener noreferrer">CompoundButton.OnCheckedChangeListener</a> interface in your main activity:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.switchcompatexample;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.widget.CompoundButton;


public class MainActivity extends ActionBarActivity implements
        CompoundButton.OnCheckedChangeListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SwitchCompat switchCompat = (SwitchCompat) findViewById(R.id
                .switch_compat);
        switchCompat.setSwitchPadding(40);
        switchCompat.setOnCheckedChangeListener(this);

        SwitchCompat switchCompat2 = (SwitchCompat) findViewById(R.id
                .switch_compat2);
        switchCompat2.setSwitchPadding(40);
        switchCompat2.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.switch_compat:
                Log.i("switch_compat", isChecked + "");
                break;
            case R.id.switch_compat2:
                Log.i("switch_compat2", isChecked + "");
                break;
        }

    }
}
</pre>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">There is not much to explain in the above code. MainActivity simply implements <a title="Android CompoundButton.OnCheckedChangeListener Interface" href="http://developer.android.com/reference/android/widget/CompoundButton.OnCheckedChangeListener.html" target="_blank" rel="noopener noreferrer">CompoundButton.OnCheckedChangeListener</a> interface to detect the state changes of Android SwitchCompat button. An interesting fact that turned up while I was developing this was that, somehow SwitchCompat does not acknowledges the padding if it is set through the xml. To set padding in an Android SwitchCompat widget you may need to do it through code, as shown above.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Hope with this <a title="Android Switch Button Example" href="http://www.truiton.com/2015/03/android-switch-button-example/">Android switch button example</a>, I would see more apps in market where a switch button can be dragged. Connect with us through Facebook, Google+, and Twitter for more Android news.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2015/03/android-switchcompat-example/">Android SwitchCompat Example</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2015/03/android-switchcompat-example/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">911</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: www.truiton.com @ 2026-07-04 05:47:48 by W3 Total Cache
-->