How to Handle Back Button Event in Fragment andorid – ViewPager Android Tutorial.

Author: | Posted in Android, Quick Tips 3 Comments

Here we will learn how to handle back button in fragment class andorid.
we will try to cover some more things also in this tutorial like
1. How to create and use a ViewPager in Android.
2. Handling Changes of Pages in ViewPager Android.
3. Working with Fragments Android.

we know that how to handle back button in our Activity. (using onBackPressed();)
and there is no back button event listner in fragment class.

to implement Back Button event in fragment follow these steps.

create a new project in eclipse. and paste a android-support-v4.jar into project libs folder after that add a ViewPager to your MainActivity layout(activity_main.xml)

<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/viewpager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</RelativeLayout>

and create two layout files for your fragments in res/layout folder.(frag_layout_one.xml)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="Swipe &lt; to see another view"
        android:textColor="#000" />
</RelativeLayout>

and frag_layout_two.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Click Me!" />
    <LinearLayout
        android:id="@+id/layoutshowhide"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_centerInParent="true"
        android:background="#ccc"
        android:gravity="center"
        android:orientation="vertical" >
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Hello"
            android:textColor="#000"
            android:textSize="24sp" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="press back button to hide this."
            android:textColor="#000" />
    </LinearLayout>
</RelativeLayout>

now create two Fragment classes for our ViewPager (FragmentOne.java)
which will be first page of our ViewPager.

package com.example.viewpagertutorial;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        final ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.frag_layout_one, null);
        return rootView;
    }
}

and for second page (FragmentTwo.java)

package com.example.viewpagertutorial;
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.Button;
import android.widget.LinearLayout;
public class FragmentTwo extends Fragment {
    Button btnClick = null;
    LinearLayout llShowView = null;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        final ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.frag_layout_two, null);
        llShowView = (LinearLayout) rootView.findViewById(R.id.layoutshowhide);
        btnClick = (Button) rootView.findViewById(R.id.buttonclick);
        btnClick.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                llShowView.setVisibility(View.VISIBLE);
            }
        });
        return rootView;
    }
    public void onBackPressed() {
        if (llShowView.getVisibility() == View.VISIBLE) {
            llShowView.setVisibility(View.GONE);
        } else {
            getActivity().finish();
        }
    }
}

now use these fragment classes in our MainActivity class(MainActivity.java)
please ensure that your MainActivity class extends FragmentActivity

package com.example.viewpagertutorial;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
public class MainActivity extends FragmentActivity {
    FragmentOne fragment_one = null;
    FragmentTwo fragment_two = null;
    int check = 0;
    ViewPager viewpager = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentPagerAdapter adapter = new ViewPagerAdapter(getApplication(),
                getSupportFragmentManager());
        viewpager = (ViewPager) findViewById(R.id.viewpager);
        viewpager.setAdapter(adapter);
        viewpager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // TODO Auto-generated method stub
                check = position;
            }
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub
            }
        });
    }
    class ViewPagerAdapter extends FragmentPagerAdapter {
        public ViewPagerAdapter(Context _contaxt, FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position) {
            Fragment f = new Fragment();
            switch (position) {
            case 0:
                fragment_one = new FragmentOne();
                f = fragment_one;
                break;
            case 1:
                fragment_two = new FragmentTwo();
                f = fragment_two;
                break;
            }
            return f;
        }
        @Override
        public int getCount() {
            return 2;
        }
    }
    @Override
    public void onBackPressed() {
        switch (check) {
        case 0:
            finish();
            break;
        case 1:
            fragment_two.onBackPressed();
            break;
        }
    }
}

now run your project and test it’s functionality. you can use and customize as per your requirement.

  • Userr Usuario

    thanks very good

  • Ashok Agarwal

    This tutorial is very helpful

  • suresh shiyani

    this is very very helpful for me thanks….