Saturday, 22 February 2014

Android Fragment Tab Example | Bottom Fragment Tab | Custom Tab Item


Hello Friends Today I will write code for Fragment Tab at Bottom .

Step 1 : Create a project BottomTabFragment

Step 2 :  MainActivity.java

package com.smart.sms;

import android.os.Bundle;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TabHost.TabSpec;

public class MainActivity extends FragmentActivity  {

private static final String TAB_1_TAG = "tab_1";
private static final String TAB_2_TAG = "tab_2";
private static final String TAB_3_TAG = "tab_3";

private FragmentTabHost mTabHost;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InitView();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();

}

private void InitView() {
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);


        mTabHost.addTab(setIndicator(MainActivity.this,mTabHost.newTabSpec(TAB_1_TAG),
                R.drawable.tab_indicator_gen,"Audio",R.drawable.genres_icon),Tab1Container.class,null);
        mTabHost.addTab(setIndicator(MainActivity.this,mTabHost.newTabSpec(TAB_2_TAG),
               R.drawable.tab_indicator_gen,"Video",R.drawable.genres_icon),Tab2Container.class,null);
        mTabHost.addTab(setIndicator(MainActivity.this,mTabHost.newTabSpec(TAB_3_TAG),
               R.drawable.tab_indicator_gen,"Latest",R.drawable.genres_icon),Tab3Container.class,null);
     
     
}

@Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();

if (currentTabTag.equals(TAB_1_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_1_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_2_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_2_TAG)).popFragment();
}
else if (currentTabTag.equals(TAB_3_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_3_TAG)).popFragment();
}

if (!isPopFragment) {
finish();
}
}

private TabSpec setIndicator(Context ctx, TabSpec spec,
int resid, String string, int genresIcon) {
      View v = LayoutInflater.from(ctx).inflate(R.layout.tab_item, null);
      v.setBackgroundResource(resid);
      TextView tv = (TextView)v.findViewById(R.id.txt_tabtxt);
      ImageView img = (ImageView)v.findViewById(R.id.img_tabtxt);
     
      tv.setText(string);
      img.setBackgroundResource(genresIcon);
      return spec.setIndicator(v);
}


}

Step 3 : activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
     <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />
            
    <android.support.v4.app.FragmentTabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dip"
            android:layout_height="0dip"
            android:layout_weight="0" />
        
    </android.support.v4.app.FragmentTabHost>
    
   
</LinearLayout>

Step 3.1 : Create a drawable folder in res and create  tab_indicator_gen.xml  ,download image from here





Step 3.2 : tab_indicator_gen.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/tab_select" android:state_selected="true"/>
    <item android:drawable="@drawable/tab_select" android:state_pressed="true"/>
    <item android:drawable="@drawable/tab_black"/>

</selector>


Step 4 : tab_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
   >

    <TextView
        android:id="@+id/txt_tabtxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/img_tabtxt"
        android:layout_marginTop="2dp"
        android:textSize="13dp"
        android:layout_centerHorizontal="true"
        android:text="Medium Text"
        android:textColor="@android:color/white"
        android:textStyle="bold"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@+id/img_tabtxt"
        android:layout_width="33dp"
        android:layout_height="30dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
    
        />

</RelativeLayout>

Step 5 : BaseContainerFragment.java

package com.smart.sms;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;

public class BaseContainerFragment extends Fragment {

public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
  transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("Ritesh", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}


Step 6 : container_framelayout.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container_framelayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    

</FrameLayout>


Step 7 : Tab1Container.java

package com.smart.sms;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Tab1Container extends BaseContainerFragment {

private boolean IsViewInited;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e("Ritesh", "Tab1");
return inflater.inflate(R.layout.container_fragment, null);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
  if (!IsViewInited) {
IsViewInited = true;
initView();
}
}

private void initView() {
replaceFragment(new AudioFragment(), false);
}

}


Step8 :  Tab2Container.java

package com.smart.sms;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Tab2Container extends BaseContainerFragment {
private boolean IsViewInited;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e("Ritesh", "Tab2");
return inflater.inflate(R.layout.container_fragment, null);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (!IsViewInited) {
IsViewInited = true;
initView();
  }
}
private void initView() {
replaceFragment(new VideoFragment(), false);
}
}

Step 9: Tab3Container.java

package com.smart.sms;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Tab3Container extends BaseContainerFragment {
private boolean IsViewInited;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e("Ritesh", "Tab3");
return inflater.inflate(R.layout.container_fragment, null);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (!IsViewInited) {
IsViewInited = true;
initView();
}
}
private void initView() {
replaceFragment(new LatestFragment(), false);
}
}

Step 10: AudioFragment.java 

package com.smart.sms;

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

public class AudioFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.audio, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
TextView tv=(TextView)getActivity().findViewById(R.id.textset);
tv.setText("Audio");
}

}

Step 11 :  audio.xml

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

    <TextView
        android:id="@+id/textset"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textColor="#00FF00"
        android:gravity="center"
        android:textSize="35sp"
        android:background="@android:color/black"
        android:textStyle="bold"

        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Step 12 : LatestFragment.java

package com.smart.sms;

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

public class LatestFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.audio, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
TextView tv=(TextView)getActivity().findViewById(R.id.textset);
tv.setText("Latest");
}

}

Step 13 : VideoFragment.java 

package com.smart.sms;

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

public class VideoFragment extends Fragment implements OnClickListener{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.audio, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
TextView tv=(TextView)getActivity().findViewById(R.id.textset);
tv.setText("Video");
tv.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
((BaseContainerFragment)getParentFragment()).replaceFragment(new VideoDescription(), true);
}

}

Step 14: VideoDescription.java 

package com.smart.sms;

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

public class VideoDescription extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.audio, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
TextView tv=(TextView)getActivity().findViewById(R.id.textset);
tv.setText("Video Description");
}

}

Step 15 : AndroidManifest 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.smart.sms"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.smart.sms.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Step 16 : Run The Project













24 comments:

  1. Hello Ritesh,

    it is very helpful post, done great job. keep it up.
    Please mention full source code download link for this example.

    Thanks
    Hasmukh

    ReplyDelete
  2. Hello Ritesh,

    it is better if you implement stack for tab fragment and child activity of tab in this sample.

    here is the link for more idea
    https://github.com/iamjayanth/FragmentTabStudy

    Thanks

    ReplyDelete
  3. Hi Ritesh,

    Very helpfull post...Thank you

    ReplyDelete
  4. Dont forget that this is not a Android design. Android does not place Tabs at the bottom. They belong at the top. Dont mimc iOS!

    ReplyDelete
  5. where is that container_fragment.xml file layout?

    ReplyDelete
  6. Please update container_fragment.xml layout

    ReplyDelete
  7. Hello,

    You code is good and easy to under. but just one thing is missing and i am not getting about container_fragment.xml missing. So please update that here or mail me

    ReplyDelete
  8. Hi…I am good at forwarding good blogs. As I found your writing fun, interesting and educative, I forwarded the link to some of my best friends. I must say…they enjoyed your article. So, when we met sometime later, I was greeted with claps and cheers. “You have finally found the best blog”, they said. All thanks to you, now I am constant looking for great work such as yours and found quite a lot of good blogs from websites like graphic design logos , unique flyer design and www.envato.com. Now, my friends are waiting to read my forwards. Happy me!

    ReplyDelete
  9. Great Tutorial its very helpful...

    ReplyDelete
  10. Very lengthy code should not used as they create unnecessary complexity.

    ReplyDelete
  11. I have checked your code, It is very useful for android developer but code is very large, beginner can not understand easily. I am an android developer and I am learning android programming from the android developer forum, they provide high quality programming and here we can ask & post all android programming questions and answers.

    Thanks

    ReplyDelete
  12. Visit viralandroid.com for android tutorials, tips and tricks, examples, etc.

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. Can you post the container_fragment.xml? 4th person to ask. I have been dying over tabs. Please ...

    ReplyDelete
    Replies
    1. Actually, if you take a look at this link (https://github.com/colaboy2004/FragmentTabHostExample/blob/master/res/layout/container_fragment.xml) and you copy that xml file into res/layout ... :)

      Delete
  15. Hello how can i change the background color of tab from green to some other ? please help me as fast as possible.

    ReplyDelete
  16. I have one query, when i minimize the my activity once intented from fragment. Again when i open the app it shows fragment view not minimized activity. could u please help me?

    ReplyDelete
  17. It's interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving... very specific nice content.
    Android training in chennai with placement | Android Training in chennai |Android Training in Velachery

    ReplyDelete
  18. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.
    Android Training in chennai | Android Training|Android Training in chennai with placement | Android Training in velachery

    ReplyDelete