Home > Mobile >  Problem with onBackPressed() ovveriding due to no window focus
Problem with onBackPressed() ovveriding due to no window focus

Time:12-03

I have an activity (ActvityMain.java) which contains a fragment (HomeFragment.java); from the fragment I start a new activity (MapActivity.java) with a button click as show here:

//code from HomeFragment.java

buttonMap.setOnClickListener(view -> {
            Intent i = new Intent(rootView.getContext(), MapActivity.class);
            requireActivity().finish();
            startActivity(i);
        });

Then from the MapActivity class I want to handle the back button click so I override onBackPressed() method to return on MainActivity class as show here:

//code from MapActivity.java

@Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent i = new Intent(ctx, MainActivity.class);
        startActivity(i);
        finish();
    }

The problem is that when I try this action on the emulator it doesn't works and I receive a message in console like:

W/ViewRootImpl[MapActivity]: Dropping event due to no window focus: KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_BACK, scanCode=0, metaState=0, flags=0x48, repeatCount=0, eventTime=12119542, downTime=12119542, deviceId=-1, source=0x101 }
W/ViewRootImpl[MapActivity]: Cancelling event due to no window focus: KeyEvent { action=ACTION_UP, keyCode=KEYCODE_BACK, scanCode=0, metaState=0, flags=0x68, repeatCount=0, eventTime=12119616, downTime=12119542, deviceId=-1, source=0x101 }

Is there anyone who knows how to solve it? Thank you

CodePudding user response:

you can try using this one:

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed()
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onBackPressed() {
        val myIntent = Intent(this, MainActivity::class.java)
        myIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
        startActivity(myIntent)
        finish()
        return
    }

CodePudding user response:

you don't need intent for going back just replace it with

getActivity().onBackPressed());

  • Related