Thursday 17 September 2015

Bottom Tabs with Fragment State PAger Adapter

Hi All, Today we learn about adding bottom tabs with fragment state pager adapter. Below code is generating four fragment pages, however you can modified it acocording to your need. Have fun :) Download Source Create a new project, and add MainApplication.java
import android.app.Application;
import android.content.Context;
public class MainApplication extends Application{
/**
* Context for Application
*/
private static Context sApplicationContext;
/**
* To get the context of the current activity
* @return Context of the current activity
*/
public static Context getsApplicationContext() {
return sApplicationContext;
}
/*
* Returning the context of the current activity
* @see android.app.Application#onCreate()
*/
@Override
public void onCreate(){
super.onCreate();
sApplicationContext = this;
}

}
Add HomeScreenActivity.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

/**
* Home Screen Activity class, having Pager adapter and bottom tabs
* @author ABHISHEK
*/
public class HomeScreenActivity extends ActionBarActivity implements OnPageChangeListener, OnClickListener,
android.content.DialogInterface.OnClickListener {
/*
* Views of this Activity
*/
private ViewPager mPager = null;
private TextView[] mBottomTabTextView = new TextView[4];
private ImageView[] mBottomTabImageView = new ImageView[4];
private TextView[] mBottomTabNameTextView = new TextView[4];
private TextView mLogout = null;
private static final int NUMBER_OF_VIEW_TO_ALIVE = 4;

// Array of drawable for their corresponding states
private int[] mBottomImageResourceUnselected = { R.drawable.photo1, R.drawable.photo2, R.drawable.photo3,
R.drawable.photo4};
//private int[] mBottomImageResourceSelected = { R.drawable.home_selected, R.drawable.mycomic_selected,
// R.drawable.search_selected };
private int[] mBottomImageResourceSelected = { R.drawable.photo1, R.drawable.photo2, R.drawable.photo3,
R.drawable.photo4};

/**
* @param isMyComicRequestSend : false to start mycomic request
*/

private HomePagerAdapter mAdapter = null;
public static HomeScreenActivity sHomeScreen = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sHomeScreen = this;
setContentView(R.layout.home_screen_activity);
ActionBar actionBar = getSupportActionBar();
LayoutInflater mInflater = LayoutInflater.from(this);

View customView = mInflater.inflate(R.layout.home_screen_action_bar, null);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(customView, new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
ActionBar.LayoutParams.MATCH_PARENT));
mLogout = (TextView) customView.findViewById(R.id.txt_view_log_out);
actionBar.setDisplayShowHomeEnabled(false); // remove app icon
actionBar.setDisplayShowTitleEnabled(false); // remove app title
actionBar.show();
initialize();
registerListener();

setTabSelected(0);
mAdapter = new HomePagerAdapter(getSupportFragmentManager());
mPager.setOffscreenPageLimit(NUMBER_OF_VIEW_TO_ALIVE);
mPager.setAdapter(mAdapter);
}

/*
* Clear the instance of comic detail screen, and delete the decrypted file
* @see android.support.v4.app.FragmentActivity#onResume()
*/
@Override
protected void onResume() {
super.onResume();

/*
* delete the Decrypted file if exist
*/
// File decryptedFile = new File(XpinnOffUtil.loadPreference(Constants.DECRYPTED_FILE_PATH));
//
// if(decryptedFile.exists()){
// decryptedFile.delete();
// XpinnOffUtil.clearPreference(Constants.DECRYPTED_FILE_PATH);
// XpinnOffUtil.clearPreference(Constants.DECRYPTED_FILE_KEY);
// }
}

/**
* Initialize activity views
*/
public void initialize() {
mPager = (ViewPager) findViewById(R.id.pager);
/*
* Initialize tab strips
*/
mBottomTabTextView[0] = (TextView) findViewById(R.id.txt_view_home_tab);
mBottomTabTextView[1] = (TextView) findViewById(R.id.txt_view_mycomic_tab);
mBottomTabTextView[2] = (TextView) findViewById(R.id.txt_view_free_tab);
mBottomTabTextView[3] = (TextView) findViewById(R.id.txt_view_search_tab);

/*
* Initialize bottom tab views
*/
mBottomTabImageView[0] = (ImageView) findViewById(R.id.img_view_home_tab);
mBottomTabImageView[1] = (ImageView) findViewById(R.id.img_view_mycomic_tab);
mBottomTabImageView[2] = (ImageView) findViewById(R.id.img_view_free_tab);
mBottomTabImageView[3] = (ImageView) findViewById(R.id.img_view_search_tab);
mBottomTabNameTextView[0] = (TextView) findViewById(R.id.txt_view_tab_home);
mBottomTabNameTextView[1] = (TextView) findViewById(R.id.txt_view_tab_mycomic);
mBottomTabNameTextView[2] = (TextView) findViewById(R.id.txt_view_tab_free);
mBottomTabNameTextView[3] = (TextView) findViewById(R.id.txt_view_tab_search);

}

/**
* Called to register Listeners
*/
public void registerListener() {
// Add loop to register listener for Bottom tab image views
for (int i = 0; i < 4; i++) {
mBottomTabImageView[i].setOnClickListener(this);
}
mPager.setOnPageChangeListener(this);
mLogout.setOnClickListener(this);
}

/**
* Called to set the tab selected
* @param iPosition : Position of the Tab to be selected
*/
public void setTabSelected(int iPosition) {
boolean state = false;
/*
* Add loop for Adding selected and unselected drawable for the image view
*/
for (int i = 0; i < 4; i++) {
if (i == iPosition) {
mBottomTabImageView[i].setImageDrawable(getResources().getDrawable(mBottomImageResourceSelected[i]));
mBottomTabNameTextView[i].setTextColor(getResources().getColor(R.color.dark_blue));
state = true;
} else {
mBottomTabImageView[i].setImageDrawable(getResources().getDrawable(mBottomImageResourceUnselected[i]));
mBottomTabNameTextView[i].setTextColor(getResources().getColor(R.color.black));
state = false;
}
mBottomTabTextView[i].setSelected(state);
}
}

/*
* @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrollStateChanged(int)
*/
@Override
public void onPageScrollStateChanged(int arg0) {
}

/*
* @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrolled(int, float, int)
*/
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {

}

/*
* @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageSelected(int)
*/
@Override
public void onPageSelected(int iPosition) {
/*
* if network is available
*/
//if position is 1 i.e mycomic and sMyComicRequest send is false
// then send my comic request
setTabSelected(iPosition);
}

/*
* Called on bottom image click
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View iView) {
/*
* if logout image is clicked
*/
if (iView.getId() == R.id.txt_view_log_out) {
showDialog();
}
/*
* if bottom tabs are clicked
*/
else {
setmPagerOnTabClick(iView.getId());
}
}

/**
* Called to set page position on corresponding image click
* @param iTabId : Bottom Tab (Image View) id
*/
public void setmPagerOnTabClick(int iTabId) {
/*
* Add loop to find the id
*/
for (int i = 0; i < 4; i++) {
/*
* If view id match, the set page position
*/
if (mBottomTabImageView[i].getId() == iTabId) {
mPager.setCurrentItem(i);
setTabSelected(i);
break;
}
}
}

/**
*Called to show Dialog for logout
*/
public void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("INFO");
builder.setMessage("EXIT_MESSAGE");
builder.setPositiveButton("OK", this);
builder.setNegativeButton("CANCEL", this);
builder.show();
}

/*
* Called on logout dialog click
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface iDialog, int iWhich) {
/*
* If ok button clicked then logout app
*/
if (iWhich == DialogInterface.BUTTON_POSITIVE) {
System.exit(0);
}
/*
* if cancel button clicked then hide the dialog
*/
else {
iDialog.dismiss();
}
}

/*
* Prompt message to logout
* @see android.support.v4.app.FragmentActivity#onBackPressed()
*/
@Override
public void onBackPressed() {
showDialog();
}

/*
* @see android.support.v4.app.FragmentActivity#onDestroy()
*/
@Override
protected void onDestroy() {
super.onDestroy();
sHomeScreen = null;
}
}
Add HomePagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

/**
* View pager Adapter of {@link HomeScreenActivity}
* @author ABHISHEK
*/
public class HomePagerAdapter extends FragmentStatePagerAdapter {

/**
* Number of Fragment pages in the view pager
*/
private static final int NUMBER_OF_PAGES = 4;
private Fragment2 mFragment2 ;
private Fragment4 mFragment4 ;
private Fragment3 mFragment3 ;
private Fragment1 mFragment1;

/**
* @return : Instance of {@link Fragment3}
*/
public Fragment3 getmFragment3() {
return mFragment3;
}

/**
* @return : Instance of {@link Fragment2}
*/
public Fragment2 getFragment2() {
return mFragment2;
}

/**
* @return : Instance of {@link Fragment4}
*/
public Fragment4 getmFragment4() {
return mFragment4;
}

/**
* {@link HomePagerAdapter} {@link Constructor}
* @param fm : {@link FragmentManager} instance
*/
public HomePagerAdapter(FragmentManager fm) {

/*
* Instantiate view pager fragments
*/
super(fm);
if(mFragment1 == null){
mFragment1 = new Fragment1();
}
if (mFragment2 == null) {
mFragment2 = new Fragment2();
}
if (mFragment4 == null) {
mFragment4 = new Fragment4();
}
if (mFragment3 == null) {
mFragment3 = new Fragment3();
}
}

/*
* Called to get the selected fragment
* @see android.support.v4.app.FragmentPagerAdapter#getItem(int)
*/
@Override
public Fragment getItem(int iPosition) {

// Match the corresponding position
switch (iPosition) {
case 0:
return getmFragment1();
case 1:
return getFragment2();
case 2:
return getmFragment3();
case 3:
return getmFragment4();
default:
return null;
}
}

public Fragment1 getmFragment1() {
return mFragment1;
}

/*
* Called to get the number of fragment pages in the view pager
* @see android.support.v4.view.PagerAdapter#getCount()
*/
@Override
public int getCount() {
return NUMBER_OF_PAGES;
}
}
In Above code, we have created adapter for four fragments. Below are four fragments and their layout, and only single layout is used for all fragments. You can create your layouts as per your need Fragment1.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class Fragment1 extends Fragment{

private ImageView mImage;
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null);
mImage = (ImageView) view.findViewById(R.id.image);
mImage.setImageResource(R.drawable.photo1);
return view;
}
}

Fragment2.java

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class Fragment2 extends Fragment{

private ImageView mImage;
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null);
mImage = (ImageView) view.findViewById(R.id.image);
mImage.setImageResource(R.drawable.photo2);
return view;
}
}

Fragment3.java

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class Fragment3 extends Fragment{

private ImageView mImage;
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null);
mImage = (ImageView) view.findViewById(R.id.image);
mImage.setImageResource(R.drawable.photo3);
return view;
}
}

Fragment4.java

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class Fragment4 extends Fragment{

private ImageView mImage;
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null);
mImage = (ImageView) view.findViewById(R.id.image);
mImage.setImageResource(R.drawable.photo4);
return view;
}
}
Add below layouts in res/layout fragment_layout.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:orientation="vertical" >
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</LinearLayout>
home_screen_action_bar.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:background="@color/white" >

<TextView
android:id="@+id/txt_view_log_out"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:gravity="center_vertical"
android:padding="@dimen/ten"
android:text="@string/logout"
android:textColor="@color/black" />

</RelativeLayout>
home_screen_activity.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.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/footer" />

<EditText
android:id="@+id/dummy_edt_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />

<LinearLayout
android:id="@+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/grey_background"
android:orientation="vertical" >

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<TextView
android:id="@+id/txt_view_home_tab"
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_weight="1"
android:background="@drawable/strip_selector" />

<TextView
android:id="@+id/txt_view_mycomic_tab"
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_weight="1"
android:background="@drawable/strip_selector" />

<TextView
android:id="@+id/txt_view_free_tab"
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_weight="1"
android:background="@drawable/strip_selector" />

<TextView
android:id="@+id/txt_view_search_tab"
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_weight="1"
android:background="@drawable/strip_selector" />
</LinearLayout>

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:orientation="horizontal" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@color/white"
android:orientation="vertical" >

<ImageView
android:id="@+id/img_view_home_tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/photo1" />

<TextView
android:id="@+id/txt_view_tab_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="@string/home" />
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@color/white"
android:orientation="vertical" >

<ImageView
android:id="@+id/img_view_mycomic_tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/photo2" />

<TextView
android:id="@+id/txt_view_tab_mycomic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/mycomic" />
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@color/white"
android:orientation="vertical" >

<ImageView
android:id="@+id/img_view_free_tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/photo3" />

<TextView
android:id="@+id/txt_view_tab_free"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/free" />
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@color/white"
android:orientation="vertical" >

<ImageView
android:id="@+id/img_view_search_tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/photo4" />

<TextView
android:id="@+id/txt_view_tab_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/search" />
</LinearLayout>
</LinearLayout>
</LinearLayout>

</RelativeLayout>
Add Selector in res/drawable
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:drawable="@color/white" android:state_selected="false"/>
<item android:drawable="@color/bright_blue" android:state_selected="true"/>

</selector>
Add color file in res/value folder colors.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Colors constants -->

<resources>

<color name = "white" >#FFFFFF</color>
<color name = "black" >#000000</color>
<color name = "grey_background" >#4F4F51</color>

<color name = "bright_blue" >#BBE5FF</color>
<color name = "dark_blue" >#1F7EC2</color>

</resources>
Add dimen file in res/values folder dimen.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!-- Constants related with dimensions used in xmls -->

<resources>

<dimen name = "ten">10dp</dimen>

</resources>
Add strings file in res/values folder strings.xml
<!-- String constants used in xmls -->
<resources>

<string name = "app_name" >Test</string>
<string name = "logout" >Log Out</string>
<string name = "home" >Home</string>
<string name = "free" >Free </string>
<string name = "mycomic" >My Comics</string>
<string name = "search" >Search</string>
<string name = "cancel" >Cancel</string>
<string name = "ok" >OK</string>

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

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

<application
android:name="com.example.test.MainApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.test.HomeScreenActivity"
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>
Note : All you need to add four images photo1.png, photo2.png, photo3.png, photo4.png  in res/drawable Download Source

No comments:

Post a Comment