Skip to content

Instantly share code, notes, and snippets.

@blessochampion
Forked from ahmedlhanafy/android.md
Created June 23, 2017 10:16
Show Gist options
  • Save blessochampion/0b735dbf639ef722097b4b48422d10ce to your computer and use it in GitHub Desktop.
Save blessochampion/0b735dbf639ef722097b4b48422d10ce to your computer and use it in GitHub Desktop.
Android Cheat Sheet

Android Cheat Sheet

Developer tips

Ripple Effect

android:clickable="true"
android:background="?attr/selectableItemBackground"

or

<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/ripple_light"/>

Record a video of your app

Developer options -> Check show touches
adb shell screenrecord /sdcard/video.mp4
adb pull /sdcard/video.mp4

Logcat while two devices connected

adb devices
adb -s SA5A330471 logcat | grep --line-buffered Playback

Easily input text

adb shell input text yourusername;
adb shell input keyevent 66;
adb shell input text yourpassword;
adb shell input text "Can%swe%sstill%sbe%sfriends"

Styles

Font family

android:fontFamily="sans-serif"                 // roboto regular
android:fontFamily="sans-serif-light"           // roboto light
android:fontFamily="sans-serif-condensed"       // roboto condensed
android:fontFamily="sans-serif-condensed-light" // roboto condensed light
android:fontFamily="sans-serif-thin"            // roboto thin (android 4.2)
android:fontFamily="sans-serif-medium"          // roboto medium (android 5.0)

ListView Adapter

myList = (ListView)findViewById(R.id.listView1);
MyAdapter adapter = new MyAdapter(this, android.R.layout.simple_list_item_1, R.id.textView1, values);
myList.setAdapter(adapter);
class MyAdapter extends ArrayAdapter<String>{

		public MyAdapter(Context context, int resource, int textViewResourceId,
				String[] objects) {
			super(context, resource, textViewResourceId, objects);
			// TODO Auto-generated constructor stub
		}
		public View getView(int position, View convertView, ViewGroup parent){
			LayoutInflater inf = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
			View v = inf.inflate(R.layout.item, parent, false);
			TextView text1 = (TextView)v.findViewById(R.id.textView1);
			TextView text2 = (TextView)v.findViewById(R.id.textView2);
			ImageView image = (ImageView) v.findViewById(R.id.imageView1);
			text1.setText(values[position]);
			text2.setText(values[position]);
			return v;
			
		}
	}

Rounded Images

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.avatar);

RoundedBitmapDrawable rounded =   RoundedBitmapDrawableFactory.create(getResources(), avatar);

rounded.setCornerRadius(bitmap.getWidth());

ImageView drawerProfile = (ImageView) drawerLayout.findViewById(R.id.drawer_profile_image);  
drawerProfile.setImageDrawable(rounded); 

Menus

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

Toolbar

How to style?

I. Declare custom styles in your style.xml file.

    <style name="ToolbarTextAppearance">  
        <item name="android:fontFamily">sans-serif-condensed</item>
        <item name="android:textColor">@android:color/white</item>
        <item name="android:shadowDx">1</item>
        <item name="android:shadowDy">1</item>
        <item name="android:shadowRadius">2</item>
        <item name="android:shadowColor">?colorAccent</item>
    </style>

    <style name="ToolbarTextAppearance.Title">  
        <item name="android:textSize">20sp</item>
    </style>

    <style name="ToolbarTextAppearance.Subtitle">  
        <item name="android:textSize">14sp</item>
    </style>

    <style name="MyToolbar">  
        <item name="theme">@style/ThemeOverlay.AppCompat.Dark</item>
        <item name="android:background">?colorPrimary</item>
        <item name="android:elevation">4dp</item>
    </style>  

II. Apply these styles to your Toolbar via style, tittleTextAppearance and subtittleTextAppearance attributes.

   <android.support.v7.widget.Toolbar  
       android:id="@+id/toolbar"
       android:layout_width="match_parent"
       android:layout_height="?actionBarSize"
       app:title="Toolbar"
       app:subtitle="Toolbars are amazing"
       app:titleTextAppearance="@style/ToolbarTextAppearance.Title"
       app:subtitleTextAppearance="@style/ToolbarTextAppearance.Subtitle"
       style="@style/MyToolbar"
       />

Toolbar with menu icons

I. Create items for every action.

    <menu 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">

        <item
            android:id="@+id/action_favorite"
            android:icon="@drawable/ic_favorite"
            app:showAsAction="always"/>

        <item
            android:id="@+id/action_search"
            android:icon="@drawable/ic_search"
            app:showAsAction="always"/>

        <item
            android:id="@+id/action_settings"
            android:orderInCategory="100"
            android:title="@string/action_settings"
            app:showAsAction="never"/>
    </menu>

II. Inflate your menu via inflateMenu method

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);  
    toolbar.inflateMenu(R.menu.main);  

II. Make your activity implement Toolbar.OnMenuItemClickListener.

    public class MyActivity extends AppCompatActivity  
        implements Toolbar.OnMenuItemClickListener {

III. Reference your activity which implements the listener in your toolbar.

    toolbar.setOnMenuItemClickListener(this);  

IV. Implement your actions inside the onMenuItemClick method.

    @Override
    public boolean onMenuItemClick(MenuItem item) {  
        switch (item.getItemId()) {
            case R.id.action_favorite:
                Toast.makeText(this, "Favorite", Toast.LENGTH_SHORT).show();
                return true;

            case R.id.action_search:
                Toast.makeText(this, "Search", Toast.LENGTH_SHORT).show();
                return true;
        }

        return true;
    }

Toolbar with navigation back icon

I. Declare custom style in your styles.xml file.

    <style name="MyToolbar">  
        <item name="theme">@style/ThemeOverlay.AppCompat.Dark</item>
        <item name="navigationIcon">@drawable/abc_ic_ab_back_mtrl_am_alpha</item>
        <item name="android:background">?colorPrimary</item>
        <item name="android:elevation">4dp</item>
    </style>  

II. Apply this style to your Toolbar via style attribute.

    <android.support.v7.widget.Toolbar  
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        app:title="Toolbar"
        app:subtitle="Toolbars are amazing"
        style="@style/MyToolbar"
        />

III. Reference a listener to handle the navigation back action.

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {  
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

Toolbar with blank space

I. Declare custom style in your styles.xml file.

    <style name="MyToolbar">  
        <item name="theme">@style/ThemeOverlay.AppCompat.Dark</item>
        <item name="navigationIcon">@drawable/abc_ic_ab_back_mtrl_am_alpha</item>
        <item name="titleMarginTop">?actionBarSize</item>
        <item name="android:background">?colorPrimary</item>
        <item name="android:elevation">4dp</item>
    </style>  

II. Apply this style to your Toolbar via style attribute.

    <android.support.v7.widget.Toolbar  
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="112dp"
        app:title="Toolbar"
        app:subtitle="Toolbars are really cool"
        style="@style/MyToolbar"
        />

Style Dialogs

How to style

I. Declare custom drawable.xml for dialog background.

    <?xml version="1.0" encoding="utf-8"?>  
    <!-- From: support/v7/appcompat/res/drawable/abc_dialog_material_background_light.xml -->  
    <inset xmlns:android="http://schemas.android.com/apk/res/android"  
        android:insetLeft="16dp"
        android:insetTop="16dp"
        android:insetRight="16dp"
        android:insetBottom="16dp">

        <shape android:shape="rectangle">
            <corners android:radius="2dp" />
            <solid android:color="@color/indigo" />
        </shape>

    </inset>  

II. Declare custom styles in your styles.xml file.

    <style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">  
        <!--item RadioButton or CheckBox color-->
        <item name="colorControlNormal">@android:color/white</item>
        <item name="colorControlActivated">@color/pink</item>
        <!--item text color-->
        <item name="textColorAlertDialogListItem">@android:color/white</item>
        <!--buttons color-->
        <item name="colorAccent">@color/pink</item>
        <!--title and message color-->
        <item name="android:textColorPrimary">@android:color/white</item>
        <!--dialog background-->
        <item name="android:windowBackground">@drawable/background_dialog</item>
    </style>  

III. Create your dialog and use style as parameter in AlertDialog.Builder.

    AlertDialog.Builder builder =  
            new AlertDialog.Builder(this, R.style.MyDialogTheme);
    ...
    AlertDialog dialog = builder.create();  
    // display dialog
    dialog.show();

Toolbar

I. In your build.gradle file add the latest design library.

dependencies {  
    compile 'com.android.support:design:X.X.X'
    // X.X.X especifica la versión
}

II. Make your Activity extend android.support.v7.app.AppCompatActivity.

public class MainActivity extends AppCompatActivity {  

III. Add the Toolbar inside an AppBarLayout, and this one inside a CoordinatorLayout.

<android.support.design.widget.CoordinatorLayout  
    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"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:elevation="@dimen/toolbar_elevation">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            style="@style/AppTheme.Widget.Toolbar"/>

    </android.support.design.widget.AppBarLayout>

    ...

</android.support.design.widget.CoordinatorLayout>  

From that point, the configuration depends on some flags described below.

Standard app bar: disappears when scrolling

The Toolbar needs to specify the following flags by using app:layout_scrollFlags:

  • scroll - it will be shown and hidden when the specified view is scrolled.
  • enterAlways - when we scroll up, the view appears immediately, instead of waiting until the scroll finishes.
  • snap - if the view remains semi-visible when scroll stops, it will be animated until it's completely shown or hidden.
    <android.support.v7.widget.Toolbar  
        ...
        app:layout_scrollFlags="scroll|enterAlways|snap"/>

You also need to specify which view you want to observe the scroll from. It can be a NestedScrollView, a RecyclerView or any other view that implements NestedScrollingChild. It is done by using app:layout_behavior:

    <android.support.v4.widget.NestedScrollView  
        ...
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

Tabs

Tabs usually stay pinned at the top when app bar hides. Add the tabs to the AppBarLayout. Previous configuration will be enough to get the expected behaviour:

    <android.support.design.widget.AppBarLayout  
        ...
    >

        <android.support.v7.widget.Toolbar
            ...
        />

        <android.support.design.widget.TabLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.DarkOverlay"/>

    </android.support.design.widget.AppBarLayout>  

Flexible space

To generate app bars with flexible size, you'll need a CollapsingToolbarLayout, used inside a CoordinatorLayout.

    <android.support.design.widget.AppBarLayout  
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:theme="@style/AppTheme.DarkOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <android.support.v7.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                tools:src="@mipmap/ic_launcher"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>  

Flexible space with image

Very similar to the previous one, but adds an ImageView to the CollapsingToolbarLayout.

    <android.support.design.widget.AppBarLayout  
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.DarkOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="200dp"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>  

Flexible space with overlapping content

The app bar is initially behind the content, and during scroll it shrinks until it gets its collapsed size. From that point, content moves behind it. app:behaviour_overlapTop will do the work.

    <android.support.design.widget.CoordinatorLayout  
        ... >

        <android.support.design.widget.AppBarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.CollapsingToolbarLayout
                android:layout_width="match_parent"
                android:layout_height="172dp"
                app:contentScrim="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"
                app:titleEnabled="false">

            <android.support.v7.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:theme="@style/AppTheme.DarkOverlay"
                android:background="@null"
                app:layout_collapseMode="pin"/>

            </android.support.design.widget.CollapsingToolbarLayout>

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            app:behavior_overlapTop="64dp"/>

    </android.support.design.widget.CoordinatorLayout>
    ```
    
    # Tabs #
![](http://www.materialdoc.com/content/images/2015/11/tabs_styled-1.png)

I. Declare custom style in your `styles.xml` file.
```xml
    <style name="TabLayoutStyle" parent="Widget.Design.TabLayout">  
        <item name="tabMaxWidth">@dimen/tab_max_width</item>
        <item name="tabIndicatorColor">@color/pink</item>
        <item name="tabIndicatorHeight">2dp</item>
        <item name="tabPaddingStart">8dp</item>
        <item name="tabPaddingEnd">8dp</item>
        <item name="tabBackground">?attr/selectableItemBackground</item>
        <item name="tabTextAppearance">@style/TabTextAppearance</item>
        <item name="tabSelectedTextColor">@android:color/white</item>
    </style>

    <style name="TabTextAppearance" parent="TextAppearance.Design.Tab">  
        <item name="android:textSize">14sp</item>
        <item name="android:textColor">@color/color_white_semitransparent</item>
        <item name="textAllCaps">true</item>
    </style>  

II. Apply this style to your TabLayout via style attribute.

    <android.support.design.widget.TabLayout  
            style="@style/TabLayoutStyle"
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

Tabs with icons and text

I. Override getPageTitle method in your ViewPager's adapter to return tab title.

    @Override
    public CharSequence getPageTitle(int position) {  
         switch (position) {
              case ITEM_ONE:
                   return "Item One";
              ...
         }
    }

II. Create selectors for every tab icon.

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

        <item
            android:state_selected="true"
            android:drawable="@drawable/ic_call_selected" />

        <item
            android:state_selected="false"
            android:drawable="@drawable/ic_call_unselected" />

    </selector>  

III. To change tab icon use TabLayout.Tab#setIcon method. You can get TabLayout.Tab object via TabLayout#getTabAt method, which accept tab index as parameter.

    ...
    //after initialization TabLayout and ViewPager
    TabLayout.Tab tabCall = tabLayout.getTabAt(ITEM_CALL);  
    tabCall.setIcon(R.drawable.selector_call);

    //repeat this code for all your tabs
    ...

Tabs with icons only

I. Create selectors for every tab icon.

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

        <item
            android:state_selected="true"
            android:drawable="@drawable/ic_call_selected" />

        <item
            android:state_selected="false"
            android:drawable="@drawable/ic_call_unselected" />

    </selector>  

II. To change tab icon use TabLayout.Tab#setIcon method. You can get TabLayout.Tab object via TabLayout#getTabAt method, which accept tab index as parameter.

    ...
    //after initialization TabLayout and ViewPager
    TabLayout.Tab tabCall = tabLayout.getTabAt(ITEM_CALL);  
    tabCall.setIcon(R.drawable.selector_call);

    //repeat this code for all your tabs
    ...

Scrollable Tabs

To make your TabLayout scrollable add custom:tabMode attribute and set it's value to scrollable.

    <android.support.design.widget.TabLayout  
            xmlns:custom="http://schemas.android.com/apk/res-auto"
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            custom:tabMode="scrollable"/>

Сentered tabs

To create centered tabs add custom:tabGravity attribute and set it's value to center.

    <android.support.design.widget.TabLayout  
            xmlns:custom="http://schemas.android.com/apk/res-auto"
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            custom:tabGravity="center"/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment