Monday 23 May 2016

Linear Constraint Layout

Linear Constraint Layout

An implementation of Cassowary, a linear constraint based layout manager in Android.
Linear Layout is the most widely used layout manager in Android. Part of the reason is that the rendering of this layout is much faster than compared to a Relative Layout. This is because the Relative Layout manager always has to do two measure passes to align views properly. But the advantage of the Linear Layout is lessened while creating complex layout structures that often require multiple nested layout elements and nested weights (read as bad performance during rendering). As an attempt to solve this problem, we have introduced a LinearConstraintLayout manager that bases its roots on the Linear Layout manager, but the view elements can be rearranged by specifying constraints.
It is based on the JAVA implementation of Cassowary which can be found here
Constraints can be specified statically (or) dynamically. For view elements that need to be placed according to some constraint, they must be placed inside the ViewGroup called LinearConstraintLayout that is defined in this project.
Constraints can be with respect to three things:
  • Depending on the position of another view element.
  • Depending on the screen's width and height
  • The view elements width or height (Eg: 200 <= Height <= 400 )
LinearConstraintLayout is a sub-class of LinearLayout and thus the rules that apply for LinearLayout also apply for LinearConstraintLayout. Eg android:orientation attribute must be specified on the LinearConstraintLayout element.

Key terms

The basic building blocks of any constraint equation are as follows:
  • self in an constraint equation refers to the current view element object itself.
  • @id/{RESOURCE_ID} refers to a view element object by the name RESOURCE_ID.
  • screen refers to the screen object.
  • x attribute of an object that corresponds to its x-position on the screen (Eg: self.x refers to the current object's x-position)
  • y attribute of an object that corresponds to its y-position on the screen (Eg: self.y refers to the current object's y-position)
  • w attribute of an object that corresponds to its width on the screen (Eg: @id/TV_Name.w refers to the width of the view element object that can be identified by the name TV_Name)
  • h attribute of an object that corresponds to its height on the screen
  • LHS = RHS specifies an equality constraint
  • LHS LEQ RHS or LHS GEQ RHS specifies an in-equality constraint

Static Constraints

The view elements must be placed into the LinearConstraintLayout ViewGroup.
<edu.gatech.constraints.library.LinearConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:constraint="http://schemas.android.com/apk/res/edu.gatech.constraints.demo"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    android:orientation="vertical"
    tools:context=".StaticDemo" >

    <TextView
        android:id="@+id/TV_DummyText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:text="@string/text1Caption"
        android:textColor="@android:color/black"
        constraint:constraint_expr="self.x = ( @id/TV_DummyText2.x + @id/TV_DummyText2.w ) - self.w"
        constraint:constraint_expr_strength="required"/>

    <TextView
        android:id="@+id/TV_DummyText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@android:color/white"
        android:text="@string/text2Caption"
        android:textColor="@android:color/black"
        constraint:constraint_expr="no_constraint"
        constraint:fixX="true"
        constraint:fixY="true" />

</edu.gatech.constraints.library.LinearConstraintLayout>
To specify constraints based on the view element itself, one could use the following attributes:
  • constraint:fixX True / False, depending on whether the view element's X (top left) position should be fixed.
  • constraint:fixY True / False, depending on whether the view element's Y (top left) position should be fixed.
  • constraint:fixWidth True / False, depending on whether the view element's width should remain fixed. Defaults to true.
  • constraint:fixHeight True / False, depending on whether the view element't height should remain fixed. Defaults totrue.
  • constraint:constraint_expr Refers to the string that specifies the constraint equation. Can also be no_constraintwhich means that a view element has no specific constraint.
  • constraint:constraint_expr_strength [Required, Strong, Medium, Weak], Refers to the strength of the constraint that is represented by the constraint_expr attribute.

Dynamic Constraints

The same constraints as above can also be specified dynamically, as shown below:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         * Declaring the root element and establishing its related parameters.
         */
        rootLayout = new LinearConstraintLayout(getApplicationContext());
        rootLayout.setBackgroundResource(android.R.color.darker_gray);
        rootLayout.setOrientation(LinearConstraintLayout.VERTICAL);

        /**
         * Defining the layout parameters for the rootLayout.
         */
        rootParams = new LinearConstraintLayout.LayoutParams(LinearConstraintLayout.LayoutParams.MATCH_PARENT,
                LinearConstraintLayout.LayoutParams.MATCH_PARENT);

        rootLayout.setLayoutParams(rootParams);

        /**
         * Declaring the first dummy text view and setting its view and layout
         * parameters including its constraints.
         * 
         * Finally, adding it to the rootView.
         */
        TextView TV_TextView1 = new TextView(getApplicationContext());
        TV_TextView1.setId(R.id.TV_DummyText1);
        TV_TextView1.setBackgroundResource(android.R.color.white);
        TV_TextView1.setTextColor(Color.BLACK);
        TV_TextView1.setText(R.string.text1Caption);

        LinearConstraintLayout.LayoutParams LP_TextView1 = new LinearConstraintLayout.LayoutParams(
                LinearConstraintLayout.LayoutParams.WRAP_CONTENT, LinearConstraintLayout.LayoutParams.WRAP_CONTENT);
        LP_TextView1.constraint_expr = "self.x = ( @id/TV_DummyText2.x + @id/TV_DummyText2.w ) - self.w";
        LP_TextView1.constraint_expr_strength = ClStrength.required;
        TV_TextView1.setLayoutParams(LP_TextView1);
        rootLayout.addView(TV_TextView1);

        /**
         * Declaring the second dummy text view and setting its view and layout
         * parameters including its constraints.
         * 
         * Finally adding it to the rootView
         */
        TextView TV_TextView2 = new TextView(getApplicationContext());
        TV_TextView2.setId(R.id.TV_DummyText2);
        TV_TextView2.setBackgroundResource(android.R.color.white);
        TV_TextView2.setTextColor(Color.BLACK);
        TV_TextView2.setText(R.string.text2Caption);

        LinearConstraintLayout.LayoutParams LP_TextView2 = new LinearConstraintLayout.LayoutParams(
                LinearConstraintLayout.LayoutParams.WRAP_CONTENT, LinearConstraintLayout.LayoutParams.WRAP_CONTENT);
        LP_TextView2.fixX = true;
        LP_TextView2.fixY = true;
        TV_TextView2.setLayoutParams(LP_TextView2);
        rootLayout.addView(TV_TextView2);
        /**
         * Set the content view to the rootLayout that was created.
         */
        setContentView(rootLayout);
    }

Constraint Satisfaction

In the case of constraints being specified for a view element, its best if the system is over-constrained to an extent. Consider the following constraint equation constraint:constraint_expr = "self.h LEQ 200dp" .
The above constraint would probably be solved by assigning the current view elements height to zero.
Cassowary is implemented such that the for a given set of constraints, the solution is a weighted sum better one. Thus the strength of the constraint plays an important role. In case the system is over-constrained, Cassowary will try to remove constraints one by one, the order of which is determined by the strength specified. By default, in our implementation, constraints such as constraint:fixXconstraint:fixYconstraint:fixWidth and constraint:fixHeight are strongconstraints.

rxFirebase

rxFirebase

RxJava wrapper on Google's Firebase for Android library.

Usage

Library provides set of static methods of classes:
  • rxFirebaseAuth
  • rxFirebaseDatabase
Authentication:
According to Firebase API there are 4 different authentication methods:
  • signInAnonymously
  • signInWithEmailAndPassword
  • signInWithCredential
  • signInWithCustomToken
    rxFirebaseAuth.signInAnonymously(FirebaseAuth.getInstance())
                .subscribe(new Action1<AuthResult>() {
                    @Override
                    public void call(AuthResult authResult) {
                        // process with authResult
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        // process auth error
                    }
                });
Database:
You can query single value like:
    rxFirebaseDatabase.observeSingleValue(firebase.child("users").child("nick"), User.class)
                .subscribe(new Action1<User>() {
                    @Override
                    public void call(User user) {
                        // process User value
                    }
                });
or the list of values:
    rxFirebaseDatabase.observeValuesList(firebase.child("posts"), BlogPost.class)
                .subscribe(new Action1<List<BlogPost>>() {
                    @Override
                    public void call(List<BlogPost> blogPosts) {
                        // process blogPosts collection
                    }
                });

Download

Gradle:
dependencies {
  compile 'com.google.firebase:firebase-auth:9.0.0'
  compile 'com.google.firebase:firebase-database:9.0.0'
  compile 'com.kelvinapps:rxfirebase:0.0.6'
}
Maven:
<dependency>
  <groupId>com.kelvinapps</groupId>
  <artifactId>rxfirebase</artifactId>
  <version>0.0.6</version>
  <type>pom</type>
</dependency>

Friday 20 May 2016

Floating Toolbar

FloatingToolbar

A toolbar that morphs from a FloatingActionButton
Available from API 14.

How to use

1. Add the following to your build.gradle:
repositories{
  maven { url "https://jitpack.io" }
}

dependencies {
  compile 'com.github.rubensousa:FloatingToolbar:0.3'
}
2. Add FloatingToolbar as a direct child of CoordinatorLayout and before the FloatingActionButton:
<android.support.design.widget.CoordinatorLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <!-- Appbar -->

    <com.github.rubensousa.floatingtoolbar.FloatingToolbar
        android:id="@+id/floatingToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="bottom"
        app:floatingMenu="@menu/main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_share_black_24dp" />


</android.support.design.widget.CoordinatorLayout>
3. Specify a menu resource file or custom layout with app:floatingMenu or app:floatingCustomView
4. Attach the FAB to the FloatingToolbar to automatically start the transition on click event:
mFloatingToolbar.attachFab(fab);
5. Set a click listener
mFloatingToolbar.setClickListener(new FloatingToolbar.ItemClickListener() {
            @Override
            public void onItemClick(MenuItem item) {

            }

            @Override
            public void onItemLongClick(MenuItem item) {

            }
        });
6. (Optional) Attach a RecyclerView to hide the FloatingToolbar on scroll:
mFloatingToolbar.attachRecyclerView(recyclerView);
7 . (Optional) Use show() and hide() to trigger the transition anytime:
mFloatingToolbar.show();
mFloatingToolbar.hide();

Attributes

  • app:floatingMenu -> Menu resource
  • app:floatingItemBackground -> Drawable resource
  • app:floatingCustomView -> Layout resource

Material Design Specs Library

Material Design Specs Library

This library provides an easy and quick way to access the entire material design color palette and elevation values, along with some neat helper methods like random access to material design colors.

Usage

To have access to the library, add the dependency to your build.gradle:
    compile 'com.androidessence:materialdesignspecs:1.0.4'
At the time of publication, the library has not yet been linked to JCenter, so you will also have to add the link to our Maven repository as well:
    repositories {
        maven {
            url  "http://dl.bintray.com/androidessence/maven"
        }
    }
Now, you'll be able to access the full color pallete from material design, either by XML, or programatically.
  • XML way
    <!-- You can use it in any view or other XML resources -->
    <!-- Access the resources by using @color/ or @dimen/ -->
    <View
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/mds_red_500"
        android:elevation="@dimen/mds_elevation_card_resting"/>
  • Java way
    // Access it through the android R file. Like the examples below.
    R.color.mds_red_500
    R.color.mds_blue_700
    R.color.mds_pink_A100
    R.color.mds_indigo_200
    // Elevations
    R.dimen.mds_elevation_card_resting
    R.dimen.mds_elevation_dialog
    R.dimen.mds_elevation_navigation_view
    R.dimen.mds_elevation_menu
You'll also have access to some static helper methods like:
    getColorsByName(String colorName) // Returns a List<Integer> of colors with the given name.
    // The methods below returns an Integer to use along your code.
    getRandomColor()
    getRandomNonAccentColor()
    getRandomColorByLevel(String colorLevel)
    getRandomColorByName(String colorName)
    getRandomColorNonRepeating()
    // And a few more!
To specify a color name or level, use the available static strings such as:
    MaterialPalettes.RED
    MaterialPalettes.LEVEL_500
Please be aware that the Integer returned by the methods above is the Integer of the resource identifier, not the color itself. So, in order to give a TextView a random text color, it would be done like this:
    Integer randomColor = MaterialPalettes.getRandomColor();
    myTextView.setTextColor(getResources().getColor(randomColor));

Sample

To see the library in action, this is the output of getting all 500 level colors and displaying them in individual TextViews:

Colors

Here's the list of the colors names. Change "X" to the color level, like "50" or "A100".
  • mds_red_X
  • mds_pink_X
  • mds_purple_X
  • mds_deeppurple_X
  • mds_indigo_X
  • mds_blue_X
  • mds_lightblue_X
  • mds_cyan_X
  • mds_teal_X
  • mds_green_X
  • mds_lightgreen_X
  • mds_lime_X
  • mds_yellow_X
  • mds_amber_X
  • mds_orange_X
  • mds_deeporange_X
  • mds_brown_X
  • mds_grey_X
  • mds_bluegrey_X
The color levels can be:
  • 50
  • 100
  • 200
  • 300
  • 400
  • 500
  • 600
  • 700
  • 800
  • 900
And the accent ones are:
  • A100
  • A200
  • A400
  • A700
Example of a color: mds_orange_A400.
Reminder: brown, grey, and bluegrey don't have accent colors.
The full color palettes as well as some more information on how to use them can be found in Google's Material Design Specifications.

Elevation values

To know which elevation value to use, please refer to the material design specs.
And with that you're all set. Go make some awesome apps with our lib :)