Thursday, 7 April 2016

Material Design Sliding Tabs


Android tab is one of the  important user interfaces (UI) design. Tabs are used at the top with Appbar or toolbar or action bar. Sometime it is used at the bottom of application.
In essence, the entirety of tab screens is Fragments, which will be handled by a View Pager. In this tutorial, you will learn to implement material design sliding tabs in your android application.

You can see material design tabs on many new and recently updated android apps. Following are the simple steps to implement material design sliding tabs in android app.

How to Make Material Design Android Sliding Tabs

Let’s start by creating new android project to implement material design sliding tab to your app with following information.

Application name: Material Design Sliding Tabs
Company Domain: androidshikho.blogspot.in/
Package name: com. androidshikho.materialslidingtabs
Minimum SDK: Android API 14

Adding Dependencies

Open build.gradle file and add compile 'it.neokree:MaterialTabs:0.11' dependency. Build.gradle file will look like below.

11)      build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "androidshikho.com.materialdesignslidingtabs"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.0'

    compile 'it.neokree:MaterialTabs:0.11'
}


  2)  Define Color Value
Open your app colors.xml file and add the following color value.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#4CAF50</color>
    <color name="colorPrimaryDark">#388E3C</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorWhite">#ffffff</color>
</resources>

3 3)      Android Application Theme
Open your app styles.xml file from res/values and change your app theme to Theme.AppCompat.Light.NoActionBar, after that add colorPrimary, colorPrimaryDark, colorAccent. Following is the complete content of styles.xml file.

FileName : res/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

       <!-- <item name="windowActionBar">false</item>
        <item name="android:textColorPrimary">#FFFFFF</item>-->
    </style>
</resources>
 4)      XML Layout File

Now it’s time to add Toolbar, MaterialTabHost and ViewPager in your xml layout file inside RelativeLayout. Give an id name to theme and add layout_height, background, subtitleTextColor, titleTextColor in Toolbar. Similarly add app:accentColor and app:primaryColor attributes in MaterialTabHost. Your XML layout file will look like below.

FileName : res/layout/activity_main.xml

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

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolBar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        app:subtitleTextColor="@color/colorWhite"
        app:titleTextColor="@color/colorWhite" />

    <it.neokree.materialtabs.MaterialTabHost
        android:id="@+id/tabHost"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_below="@+id/toolBar"
        app:accentColor="@color/colorAccent"
        app:primaryColor="#4CAF50" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tabHost" />

</RelativeLayout>
 5)  Java Activity File
First, create a new java file called AndroidFragment.java and extend Fragment. Override onCreateView and add a text view with text and gravity center. Following is the complete java code of AndroidFragment.java file.

FileName : src/AndroidFragment.java

package androidshikho.com.materialdesignslidingtabs;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class AndroidFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        TextView textView = new TextView(container.getContext());
        // tab page content
        textView.setText("Android Tab Content");
        textView.setGravity(Gravity.CENTER);
        return textView;
    }
}

Now open your main activity java file and extend with ActionBarActivity and implement MaterialTabListener. Declare toolbar, tab host and view pager in activity file. Here you need to override onTabSelected, onTabReselected and onTabUnselected. Following is the complete java code of MainActivity.java.

FileName : src/MainActivity.java
package androidshikho.com.materialdesignslidingtabs;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;

import it.neokree.materialtabs.MaterialTab;
import it.neokree.materialtabs.MaterialTabHost;
import it.neokree.materialtabs.MaterialTabListener;

public class MainActivity extends ActionBarActivity implements MaterialTabListener {

    MaterialTabHost tabHost;
    ViewPager viewPager;
    ViewPagerAdapter androidAdapter;
    Toolbar toolBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //android toolbar
        toolBar = (android.support.v7.widget.Toolbar) this.findViewById(R.id.toolBar);
        this.setSupportActionBar(toolBar);

        //tab host
        tabHost = (MaterialTabHost) this.findViewById(R.id.tabHost);
        viewPager = (ViewPager) this.findViewById(R.id.viewPager);

        //adapter view
        androidAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(androidAdapter);
        viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int tabposition) {
                tabHost.setSelectedNavigationItem(tabposition);
            }
        });

        //for tab position
        for (int i = 1; i < androidAdapter.getCount(); i++) {
            tabHost.addTab(
                    tabHost.newTab()
                            .setText(androidAdapter.getPageTitle(i))
                            .setTabListener(this)
            );
        }
    }

    //tab on selected
    @Override
    public void onTabSelected(MaterialTab materialTab) {

        viewPager.setCurrentItem(materialTab.getPosition());
    }

    //tab on reselected
    @Override
    public void onTabReselected(MaterialTab materialTab) {

    }

    //tab on unselected
    @Override
    public void onTabUnselected(MaterialTab materialTab) {

    }

    // view pager adapter
    private class ViewPagerAdapter extends FragmentStatePagerAdapter {

        public ViewPagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        public Fragment getItem(int num) {
            return new AndroidFragment();
        }

        @Override
        public int getCount() {
            return 8;
        }

        @Override
        public CharSequence getPageTitle(int tabposition) {
            return "Tab " + tabposition;
        }
    }
}



That’s all. Run your Android Material Design Sliding Tabs application, slide right and left the tabs; they are changing which will look like above screenshot. Further you can customize according to your needs. 



Tuesday, 5 April 2016

Android SearchView Example

Search View is  most useful UI  widget/components in android. Android search view widget can be used in action bar/ appbar/ toolbar or in your layout. Both search widget and dialog are used to search text, video, etc. In this tutorial, you will learn to implement search view widget in android application.

There are two types of search.
1)      Search widget
2)     Search dialog.


 Search widget is placed anywhere in your app layout and search dialog is a UI component that is controlled by the android system. Search dialog appears at the top of activity.


How to Add Search Function to Android App


1)Create a new android studio project with the project name Simple Android SearchView. Open your XML layout file and add a search view widget with id. Following is the complete content of XML layout file.

FileName: res/layout/searchview_android_example.xml

<?xml version="1.0" encoding="utf-8"?>

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

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="wrap_content"
        android:elevation="2dp"
        android:background="#fff"
        android:layout_height="wrap_content">
    </SearchView>

</LinearLayout>

2)Now open your java activity file and set searchView.setOnQueryTextListener and then override onQueryTextSubmit and onQueryTextChange method. Following is the complete code of java activity file.

FileName: src/SimpleAndroidSearchViewExample.java

package androidshikho.com.androiduserinterfacetutorial;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.SearchView;
import android.widget.Toast;

public class SimpleAndroidSearchViewExample extends AppCompatActivity{

    SearchView searchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.searchview_android_example);

        searchView=(SearchView) findViewById(R.id.searchView);
        searchView.setQueryHint("Search View");

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                Toast.makeText(getBaseContext(), query, Toast.LENGTH_LONG).show();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Toast.makeText(getBaseContext(), newText, Toast.LENGTH_LONG).show();
                return false;
            }
        });
    }
}


3)Following is the content of styles.xml and AndroidManifest.xml file.

FileName: res/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        
    </style>

</resources>

4) Change the  AndroidManifest file
FileName: AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>

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

    package="androidshikho.com.androiduserinterfacetutorial">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".SimpleAndroidSearchViewExample">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



Now, run your SearchView Example application and click on the search icon which will look like above screenshot. If you type something in the search box the text will appear in toast in real time. 

What is Android?

Android is an open source and Linux-based Operating Systemfor mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies.
Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android.
The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 where as the first commercial version, Android 1.0, was released in September 2008.
On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance.
The source code for Android is available under free and open source software licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public License version 2.