Wednesday 18 July 2018

Navigation-OnBackPressed-To-Back-To-HomePage

            Navigation-OnBackPressed-To-Back-To-HomePage

Find the code in GitHub: Go to GitHub page


1. Create a project with navigation drawer activity

Pre-added files

i) res-layout folder
activity_main.xml
app_bar_main.xml
content_main.xml
nav_header.xml

ii) java-main-folder
MainActivity.java


2. Create one common XML file for fragment and app_bar_main.xml files changes

common_fragment.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
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">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:text="Fragment"
android:textAllCaps="true"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
android:textStyle="bold"/>
</android.support.constraint.ConstraintLayout>



app_bar_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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="www.abhiandroidknowledge.blogspot.com.navigationbackpressedtogohomepagefragement.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="@+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>


3. Add some method in MainActivity.java

MainActivity.java

private Fragment fragment = null;
private Boolean exit = false;

method 1-:
public void setFragment(int position, Class<? extends Fragment> fragmentClass) {
    DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    try {
        fragment = fragmentClass.newInstance();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.frame_layout, fragment);
        transaction.commit();
        mDrawerLayout.closeDrawer(GravityCompat.START);
    } catch (Exception ex) {
        Log.e("setFragment", ex.getMessage());
    }
}


method 2:-

@Overridepublic void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else if (exit) {
        super.onBackPressed();
        return;
    }

    try {
        if (fragment != null) {
            if (fragment instanceof HomeFragment) {
                if (fragment.isVisible()) {
                    this.exit = true;
                    Toast.makeText(this, "Press Back again to Exit", Toast.LENGTH_SHORT).show();
                }
            } else {
                setFragment(0, HomeFragment.class);
            }
        } else {
            setFragment(0, HomeFragment.class);
        }
    } catch (Exception e) {

    }
    new Handler().postDelayed(new Runnable() {
        @Override        public void run() {
            exit = false;
        }
    }, 2000);
}

4. Create two fragment HomeFragment.java and GalleryFragment.java

HomeFragment.java

package www.abhiandroidknowledge.blogspot.com.navigationbackpressedtogohomepagefragement;

import android.os.Bundle;
import android.support.annotation.NonNull;
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.TextView;

/** * Created by www.abhiandroidknowledge.blogspot.com on 18/7/18. */
public class HomeFragment extends Fragment {

    @Nullable    @Override    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.common_fragment, container, false);
        TextView tv = (TextView) view.findViewById(R.id.textView);
        tv.setText("Home Fragment");
        return view;
    }
}

GalleryFragment.java

package www.abhiandroidknowledge.blogspot.com.navigationbackpressedtogohomepagefragement;

import android.os.Bundle;
import android.support.annotation.NonNull;
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.TextView;

/** * Created by www.abhiandroidknowledge.blogspot.com on 18/7/18. */
public class GalleryFragment extends Fragment{

    @Nullable    @Override    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.common_fragment, container, false);
        TextView tv = (TextView) view.findViewById(R.id.textView);
        tv.setText("Gallery Fragment");
        return view;
    }
}


5.Replace your own actions

@SuppressWarnings("StatementWithEmptyBody")@Overridepublic boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        setFragment(1, HomeFragment.class);
    } else if (id == R.id.nav_gallery) {
        setFragment(1, GalleryFragment.class);
    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

 MainActivity.java full java file
package www.abhiandroidknowledge.blogspot.com.navigationbackpressedtogohomepagefragement;
import android.os.Bundle;import android.os.Handler;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.NavigationView;import android.support.design.widget.Snackbar;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentTransaction;import android.support.v4.view.GravityCompat;import android.support.v4.widget.DrawerLayout;import android.support.v7.app.ActionBarDrawerToggle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Toast;
/** * Created by www.abhiandroidknowledge.blogspot.com on 18/7/18. */
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private Fragment fragment = null;
    private Boolean exit = false;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        setFragment(0, HomeFragment.class);
    }


    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.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);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            setFragment(1, HomeFragment.class);
        } else if (id == R.id.nav_gallery) {
            setFragment(1, GalleryFragment.class);
        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    public void setFragment(int position, Class<? extends Fragment> fragmentClass) {
        DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        try {
            fragment = fragmentClass.newInstance();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.frame_layout, fragment);
            transaction.commit();
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } catch (Exception ex) {
            Log.e("setFragment", ex.getMessage());
        }
    }


    @Override    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else if (exit) {
            super.onBackPressed();
            return;
        }

        try {
            if (fragment != null) {
//check the instanceof home page when false then popup fragment
                if (fragment instanceof HomeFragment) {
                    if (fragment.isVisible()) {
                        this.exit = true;
                        Toast.makeText(this, "Press Back again to Exit", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    setFragment(0, HomeFragment.class);
                }
            } else {
                setFragment(0, HomeFragment.class);
            }
        } catch (Exception e) {

        }
        new Handler().postDelayed(new Runnable() {
            @Override            public void run() {
                exit = false;
            }
        }, 2000);
    }
}



************************************************************************
                           Thank you

No comments:

Post a Comment