Saturday, 26 September 2015

How to create Android Toolbar


This tutorial is going to explain about how to get rid off old fashioned action bar by replacing it with toolbar.

Time needed:
5-6 minutes

Requirements:
1) Android studio(try to keep latest version)

Theory:
Before API level 21, every developer has used action bar. But in API level 21, google  has come up with toolbar. Toolbar is a generalization of action bars. It means that you can use a toolbar as an action bar. But  action bar can only be placed at the top in the layout hierarchy. Whereas with toolbar, you have an option to place it at any arbitrary level of nesting within a view hierarchy.
To get more information related to toolbar, refer this link .

Implementation:
1) Create a new project.

2) Now under res->values->color.xml file, add colors that we want to give to toolbar and the status bar.
Note: if you do not find color.xml file, then create one.

<color name="primaryColor">#FF1D15</color>
    <color name="primaryDarkColor">#BF0603</color>
Finally, color.xml file will look like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primaryColor">#FF1D15</color>
    <color name="primaryDarkColor">#BF0603</color>
</resources>
3) As we are implementing toolbar, we need to remove the action bar. Go to res-->values-->styles.xml and change parent theme to "Theme.AppCompat.Light.NoActionBar". Also set colorPrimary and colorPrimaryDark item's. And finally, it should look like this:
<resources>

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

</resources>
4) As we need a toolbar layout in our activity_main.xml file, and we can add it directly into it's layout. But toolbar is going to implement again and again in your activities. So, in order to get rid off typing same code again, we are going to create a separate layout for toolbar.
Create tool_bar.xml under layout folder.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    android:id="@+id/tool_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/primaryColor"
    xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.Toolbar>

5) Include the toolbar (mention in layout tool_bar.xml file ) to activity_main.xml file.Finally, activity_main.xml will look like this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <include
        layout="@layout/tool_bar">
    </include>

</LinearLayout> 
6) In MainActivity.java, in onCreate method add the following code
Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
Here, we are fetching reference of toolbar layout and setting it as an action bar of our activity. Also import toolbar widget class
import android.support.v7.widget.Toolbar;

That's it...

Thursday, 24 September 2015

How to make Android Sliding Tabs



This Tutorial is about creating sliding tabs. As you can see a demo on the right side. Here, we have created 2 tabs named Home and Menu.

Time needed for creating:
10 -15 minutes


Requirements:
1) Android studio (try to keep latest version)
2) Download these two java files

Theory:
To get better understanding of this tutorial, let's start with the layout we are going to create for this tutorial.

For sliding tab, we are going to use LinearLayout with three parts.
1) Toolbar
If you do not know how to create a toolbar, then refer this link How to create Android Toolbar

2) SlidingTabLayout 
It is a layout which will act as a Tab strip. You can place it anywhere in your LinearLayout but I would prefer to put it just below the toolbar.

3) ViewPager
ViewPager is a widget in the form of java class which let user swipe right and left horizontally to see entirely new screen.
We are going to use fragment in conjunction with ViewPager.


Implementation:
1) create a new project.

2) Add both downloaded java files.

3)Now add a new color in color.xml file under res -->values folder. It is a color to highlight the selected tab.
Finally, color.xml file should look like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primaryColor">#FF1D15</color>
    <color name="primaryDarkColor">#BF0603</color>
    <color name="tabsSelectedColor">#C13936</color>
</resources>
4) As we are implementing toolbar, we need to remove the action bar. Go to res-->values-->styles.xml and change parent theme to "Theme.AppCompat.Light.NoActionBar". And finally, it should look like this:
<resources>

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

</resources>
5) Create tab1.xml under layout folder.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello friends"/>

</LinearLayout> 
and also tab2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="i am good"/>

</LinearLayout>
These are the layout files for both tabs.

6) Create Tab1.java file 
package com.example.pilot.android4learning;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class Tab1 extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.tab1, container, false);
    }
}
and Tab2.java file. 
package com.example.pilot.android4learning;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Tab2 extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.tab2,container,false);
    }
}
7)  Create a ViewPageAdapter.java file.
package com.example.pilot.android4learning;


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;


public class ViewPageAdapter extends FragmentStatePagerAdapter {

    CharSequence Titles[];
    int numberOfTitles;

    /*let's create a constructor for ViewPagerAdapter
    * In constructor we are passing 3 arguemnets
    * 1) fm -- FragmentManager
    * A FragmentManager manages Fragments in Android, specifically it handles transactions
    * between fragments. A transaction is a way to add, replace, or remove fragments.
    * 2) mTitles[] -- name of Tabs
    * 3) mNumberOdTitles -- number of tabs*/
    public ViewPageAdapter(FragmentManager fm, CharSequence mTitles[], int mNumberOfTitles){
        super(fm);
        this.Titles=mTitles;
        this.numberOfTitles=mNumberOfTitles;
    }

    @Override
     public Fragment getItem(int position){
        if(0 == position){
            Tab1 tab1 = new Tab1();
            return tab1;
        }
        else{
            Tab2 tab2 = new Tab2();
            return tab2;
        }
    }

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

    @Override
    public CharSequence getPageTitle(int position){
        return Titles[position];
    }
} 
8) We need a toolbar layout in our activity_main.xml file, and we can add it directly into it's layout. But toolbar is going to implement again and again in your activities. So, in order to get rid off typing same code again, we are going to create a separate layout for toolbar.
Create tool_bar.xml under layout folder.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    android:id="@+id/tool_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/primaryColor"
    xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.Toolbar>
9) Include the toolbar (mention in layout tool_bar.xml file ) to activity_main.xml file.
<?xml version="1.0" encoding="utf-8"?>
<include
        layout="@layout/tool_bar">
    </include>
10)Also add SlidingTabLayout and ViewPager to activity_main.xml. Finally, activity_main.xml will look like this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <include
        layout="@layout/tool_bar">
    </include>

    <com.example.pilot.android4learning.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/primaryColor">

    </com.example.pilot.android4learning.SlidingTabLayout>

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

    </android.support.v4.view.ViewPager>

</LinearLayout>

11) In MainActivity.java, in onCreate method add the following code
toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);

        //getSupportFragmentmanager -- Return the FragmentManager for interacting with fragments
        // associated with this activity
        viewPageAdapter = new ViewPageAdapter(getSupportFragmentManager(),Titles, numberOfTitles);
        pager = (ViewPager)findViewById(R.id.pager);
        pager.setAdapter(viewPageAdapter);

        tabs = (SlidingTabLayout)findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // it is to evenly distribute each tab in the layout

        /* let's change tab selected highlight color with our color.xml tabsSelctedColor.
        * setCustomTabColorizer take TabColorizer as an arguement(check this method in SlidingTabLayout)
        * which further calls getIndicatorColor method which returns default color. We override that
        * getIndicatorColor method and made it return the color that we want to set*/
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.tabsSelectedColor);
            }

        });

        tabs.setViewPager(pager);


Finally, MainActivity.java file will look like this:
package com.example.pilot.android4learning;

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    ViewPageAdapter viewPageAdapter;
    ViewPager pager;
    SlidingTabLayout tabs;
    CharSequence Titles[] = {"Home", "Menu"};
    int numberOfTitles=2;

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

        toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);

        //getSupportFragmentmanager -- Return the FragmentManager for interacting with fragments
        // associated with this activity
        viewPageAdapter = new ViewPageAdapter(getSupportFragmentManager(),Titles, numberOfTitles);
        pager = (ViewPager)findViewById(R.id.pager);
        pager.setAdapter(viewPageAdapter);

        tabs = (SlidingTabLayout)findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // it is to evenly distribute each tab in the layout

        /* let's change tab selected highlight color with our color.xml tabsSelctedColor.
        * setCustomTabColorizer take TabColorizer as an arguement(check this method in SlidingTabLayout)
        * which further calls getIndicatorColor function which returns default color. We override that
        * getIndicatorColor method and made it return the color that we want to set*/
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.tabsSelectedColor);
            }

        });

        tabs.setViewPager(pager);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
That's it...


Monday, 14 September 2015

Creating an Activity on Button Click

Activity: Activity is a java class that we use in Android Development. It takes care of creating a new window for developers in which you can place your UI(user interface). Well, activities can be of any type, it can be a full-screen window, a floating window or even embedded inside of another activity.



Here, we are going to create a new Activity by clicking on Button.

1) First create a new Project and name it "MyActivity"

2) Now create a new Blank Activity.
     Go to app->java and right click on it.
     Go to New->Activity->BlankActivity
     Now give "NewActivity" as Activity name.


3) In app->res->layout->activity_main.xml, file write this code

<Button
        android:id="@+id/press_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/press"
        android:layout_centerInParent="true"/>

your activity_main.xml file should look like this:  
  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button

        android:id="@+id/press_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/press"
        android:layout_centerInParent="true"/>

</RelativeLayout>
    
4) Go to app->res->values->strings.xml and add the below line

<string name="press">Press</string>
 
5) Now add the below code in onCreate function of your MainActivity.java file

Button Press = (Button)findViewById(R.id.press_button);
        Press.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent myActivity = new Intent(getBaseContext(),NewActivity.class);
                startActivity(myActivity);
            }
        });

finally, your onCreate function will look like:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button Press = (Button)findViewById(R.id.press_button);
        Press.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent myActivity = new Intent(getBaseContext(),NewActivity.class);
                startActivity(myActivity);
            }
        });
    }

Note: import Intent library ,
           import android.content.Intent;
         import android.view.View;
           import android.widget.Button;


6) Now go to app->res->layout-activity_new.xml and add this code

 <TextView
        android:text="@string/button_pressed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
finally, activity_new.xml should look like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.company.entertainmentbucket.myactivity.NewActivity">

    <TextView

        android:text="@string/button_pressed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

7) Go to app->res->values->strings.xml and add the below line

<string name="button_pressed">Button is Pressed</string>

That's it....

 
 


Sunday, 13 September 2015

Migrating from Eclipse to Android Studio



Now a days, developers are often migrating from Eclipse to Android Studio. And the Reason is quite simple, Android studio is better IDE than Eclipse. See this post to get more info Which IDE is good, Eclipse or Android Studio. But what if you already have your project built in Eclipse IDE and you want to migrate that project to Android Studio. Well guys, it's quite easy to do and all thanks to Android Studio for making it possible.
Migration is possible in two ways:
1) Importing your Eclipse project from Android Studio
2) Exporting your project from Eclipse

The Directory structure of Eclipse Project is different than that in Android Studio. So While migrating from Eclipse to Android Studio, your directory structure of project will get changed a lot. Migrating to Android Studio through importing from Android Studio is a quick and easy way to go but the problem is with the change in the directory structure. So if you want keep your Eclipse directory structure too then exporting from Eclipse is a way to do it.

1) Importing your Eclipse Project from Android Studio
Android Studio has really made the migration process a lot easy for the Developers. You just have to select your Eclipse Project from Android Studio and it will automatically make changes to your Eclipse Project and make it running on your new IDE in no time. These changes include replacing any jar files and libraries with Gradle dependencies and replacing source libraries and binary libraries, with Maven dependencies. Therefore, no need to maintain these files manually.

Steps:
a) Start Android Studio and click on Import Project. 
 

b) Select the Eclipse Project that you want to import and click ok.


c) Click Next.


d) Click Finish.


And you are Done....


2) Exporting your Project from Eclipse
Before exporting, check that Eclipse ADT is up to date or not(you will need version 22.0 or higher). Just go to Help->Check for Updates.  If there is an update then do update it.
a) Go to File->Export
b) Click on Generate Gradle build files


c) Click Next.


d) Select your Project.


e) Click Finish.


f) Then Eclipse will show you the path for the generated build.gradle.


g) Start Android Studio and Click on Import Project.


h) Select the generated build.gradle file (located in your project generated by Eclipse)

Note: if you found error related "failed to sync Gradle project"

then click on Fix Plugin version and sync project.

And you are done....

Saturday, 12 September 2015

Which IDE is good, Eclipse or Android Studio




Well, People Keep on asking, which IDE(Integrated Development Environment) should be a good choice to start android development. There has always been an issue with the beginners. Google's Android Studio came alive in December 2014 and Eclipse has been there even before that. So developers who has been working on android development are using Eclipse for a very long time. The day Google announced it's first stable version of Android Studio, It was really difficult for the developers to switch from Eclipse to Android Studio as the IDE are quite different. But later on, developers started realizing the strength of Android Studio. So Let's talk about it a little more.

User Interface(Ui)
Eclipse is not an Android IDE but a java IDE. Using Eclipse's Android plugin, we can integrate Android Development Environment in Eclipse. That's why it's interface is quite complicated to catch up with. Developers who has been using Eclipse for long time finds easy to work in that environment as they got used to it.
   On the other hand, Android Studio is specifically designed for only Android Development. First-time app developers, definitely finds Android Studio quite easier than manually configuring Eclipse. The User Interface is so native that you will find it helpful.

Apache Ant vs Gradle
Java Developers who has been coding for a very long time are very well aware of Apache Ant build System, which comes with Eclipse(via plugin). It actually helps in building process like a Make but the difference is that Ant uses XML files to describe build process and normally the file is build.xml.
    whereas Android Studio is way ahead in build system too. It uses the Gradle build system along with Groovy DSL. It is more advanced and offers better convenience as compared to Eclipse's Apache Ant.

Workspace(eclipse)/Modules(android studio)
Eclipse has sub-projects and workspaces. In Eclipse, the components and the libraries of the android project have to compiled in 'jar' files. Adding 3rd party libraries is to be done manually by downloading and adding it into the libs folder of the project.
     While in Android studio, each module needs to have it's own Gradle build. Adding 3rd party libraries has become very easy with gradle. Just add the reference to the module's build.gradle file, state the required version, and it will automatically fetched from the remote repository, compiled and included without having to worry about it. Gradle saves a lot of time. After adding the reference into the build.gradle, do not forget to sync the file.

Structure Eclipse Android Studio
Android Manifest [project] [module]/src/name
Assets [project]/assets [module]/src/main/assets
Java source files [project]/src [module]/src/main/java
Resources [project]/res [module]/src/main/res
Included jars [project]/libs [module]/libs

Apart from the names, they are pretty the same.

Code Completion/Refactoring feature:
 Theres  is not much of a difference in both of the IDE in this regard. Both Eclipse and Android Studio offers a pretty high-end java auto complete feature for developers. But if you really want to make a decision on this basis, do choose Android Studio over Eclipse, the code completion of Android Studio is better than Eclipse- due to the in-depth IntelliJ IDEA support. IntelliJ IDEA makes code completion less prone or Android Studio. This gives it an Edge over Eclipse.

Performance
Android Studio is way ahead to Eclipse. Eclipse is slow and hangs a lot. The hardware configuration required for Eclipse is quite more than Android Studio. Eclipse require a large amount of RAM to run as it is much larger IDE than Android Studio.  It also require a high CPU speed, particularly at the time of exporting apk files. Also there has been reports of Eclipse getting crash or erratic behaviour.
Where Android Studio is still in development but much better in performance than Eclipse. It also crashes and freezes some times but provide more promising results as compared to Eclipse. It takes around 2-3 minutes for building the final release versions of projects. Performing the same task in Android Studio does not take more than 40 seconds(even for the long and complicated codes).

Lint feature:
Android Studio uses Lint by default. You can include lint in your gradle file. If Lint finds some warnings, it will automatically abort your release process.

Need for Lint:
It forces you to use good Android development practices(like defining all your dimensions in separate XML files, or avoiding hardcoded strings). Lint also helps in pointing out the unused resource files, which at the end results in smaller APK file. Lint also handles the mistakes or unused permissions in the manifest file,etc. In order to produce quality code, you should use Android Studio with Lint in spite of Eclipse.

Cloud Platform Support:
Eclipse as well as Android Studio, both have Google cloud Support. Whereas Android Studio has it built in and Eclipse has Google plugin that can be integrated to get cloude platform support. Therefore, regarding this Both are in the same place.

App Testing and Debugging
One of the most important steps in the software development environment is testing to avoid bugs and error. In Android Studio you can define your tests in separate classes and launch them while building your applications. This way errors and bugs can be detected with ease. Android Studio let you do this in build stage of application while Eclipse does not have similar tool for easy app testing.


Conclusion:
Android Studio is getting better IDE than Eclipse. Eclipse realizes this and not going to give up easily. So it is not easy to say which is going to be the better in future. But according to the present status, Android Studio seems much promising to exists in future. Google is putting all efforts in eliminating Eclipse Android IDE.
On Google's android development site, they have already stated :

"Important: Support for the Android Developer Tools (ADT) in Eclipse is ending, per our announcement. You should migrate your app development projects to Android Studio as soon as possible. For more information on transitioning to Android Studio, see Migrating to Android Studio. "

Hence, for beginners, i would recommend Android Studio but if you are already using Eclipse then do complete your project in Eclipse and then try Android Studio Platform.