Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when back button pressed in fragment android?

I have project with navigation drawer with fragment, with 5 menu, the problem is when i go to menu 4 and the i press the back button the app closed, but i need the app back to first menu which is all the menu in fragment.

This is code for Main Activity (Navigation Drawer)

public class MainActivity extends AppCompatActivity{
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    /**
     *Setup the DrawerLayout and NavigationView
     */

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;

    /**
     * Lets inflate the very first fragment
     * Here , we are inflating the TabFragment as the first Fragment
     */

    mFragmentManager = getSupportFragmentManager();
    mFragmentTransaction = mFragmentManager.beginTransaction();
    mFragmentTransaction.replace(R.id.containerView,new Recommendation()).commit();
    /**
     * Setup click events on the Navigation View Items.
     */

    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            mDrawerLayout.closeDrawers();



            if (menuItem.getItemId() == R.id.nav_item_lux_level_recomen) {
                FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.containerView,new Recommendation()).commit();

            }

            if (menuItem.getItemId() == R.id.nav_item_room_index_calc) {
                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                xfragmentTransaction.replace(R.id.containerView,new RoomIndex()).commit();
            }

            if (menuItem.getItemId() == R.id.nav_item_utilization_factor_calc) {
                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                xfragmentTransaction.replace(R.id.containerView,new UtilizationFactorCalculator()).commit();
            }

            if (menuItem.getItemId() == R.id.nav_item_conversions) {
                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                xfragmentTransaction.replace(R.id.containerView,new Conversion()).commit();
            }
            if (menuItem.getItemId() == R.id.nav_item_lux) {
                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                xfragmentTransaction.replace(R.id.containerView,new LuxSensor()).commit();
            }


            return false;
        }

    });

    /**
     * Setup Drawer Toggle of the Toolbar
     */

    android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
    ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, toolbar,R.string.app_name,
            R.string.app_name);

    mDrawerLayout.setDrawerListener(mDrawerToggle);

    mDrawerToggle.syncState();




}

This one of the Menu (Fragment)

public class LuxSensor extends Fragment {
TextView textLIGHT_available, textLIGHT_reading;
FragmentManager mFragmentManager;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View x =  inflater.inflate(R.layout.lux_sensor,null);
    textLIGHT_reading
            = (TextView)x.findViewById(R.id.LIGHT_reading);

    SensorManager mySensorManager = (SensorManager)getActivity().getSystemService(Context.SENSOR_SERVICE);

    Sensor LightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    if(LightSensor != null){
        mySensorManager.registerListener(
                LightSensorListener,
                LightSensor,
                SensorManager.SENSOR_DELAY_NORMAL);

    }else{
        textLIGHT_available.setText("Sensor.TYPE_LIGHT NOT Available");
    }
    FragmentManager fm = getFragmentManager();

    return x;
}





private final SensorEventListener LightSensorListener
        = new SensorEventListener(){

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if(event.sensor.getType() == Sensor.TYPE_LIGHT){
            textLIGHT_reading.setText(event.values[0]+" LUX");
        }
    }

};

}

I have tried solution in internet but it still closed

like image 602
Josh Parinussa Avatar asked Mar 17 '17 13:03

Josh Parinussa


People also ask

How can I tell if back button is pressed in fragment?

You also need to check Action_Down or Action_UP event. If you will not check then onKey() Method will call 2 times. Also, If your rootview(getView()) will not contain focus then it will not work. If you have clicked on any control then again you need to give focus to rootview using getView().

Can we use onBackPressed in fragment?

As the Fragment lifecycle do not have onBackPressed() .

How do I disable back press in fragment?

Here is the new way you can manage your onBackPressed() in fragment with the new call back of activity: // Disable onBack click requireActivity(). onBackPressedDispatcher. addCallback(this) { // With blank your fragment BackPressed will be disabled. }

What is the use of addToBackStack in Android?

addToBackStack. Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.


2 Answers

In fragment you should use something like this:

  @Override
    //Pressed return button - returns to the results menu
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){

                 //your code

                   return true;
                }
                return false;
            }
        });
    }
like image 77
Catarina Ferreira Avatar answered Sep 19 '22 22:09

Catarina Ferreira


onCreateView of fragment add this

Java

requireActivity().getOnBackPressedDispatcher().addCallback(activity, new OnBackPressedCallback(true) {
    @Override
    public void handleOnBackPressed() {
        // in here you can do logic when backPress is clicked
    }
});

Kotlin

requireActivity().onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        // in here you can do logic when backPress is clicked
    }
})
like image 34
Deeptimay Routray Avatar answered Sep 23 '22 22:09

Deeptimay Routray