onBackPressed() is not working - android

In One Activity class I am using different layouts.
By disabling one layout I am moving to another layout. But I am facing an issue while pressing the back button. It is coming to the first layout while I am in third layout.
Here is my Code:
I have used 3 buttons to move to another layout.
public void continueToDelivery(View view) {
relativeLayoutLogin.setVisibility(view.GONE);
relativeLayoutDelivery.setVisibility(view.VISIBLE);
relativeLayoutPayment.setVisibility(view.GONE);
}
public void continueToPayment(View view) {
relativeLayoutDelivery.setVisibility(view.GONE);
relativeLayoutPayment.setVisibility(view.VISIBLE);
}
public void placeOrder(View view) {
relativeLayoutPayment.setVisibility(view.GONE);
relativeLayoutSuccess.setVisibility(view.VISIBLE);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}

Override onBackPressed in your activity then:
#Override
public void onBackPressed() {
if(isThirdLayoutVisible)
//go to second layout
else if(isSecondLayoutVisible)
//go to first layout
else
//exit from app
}

Related

Show a Blank Page on Back Pressed Button

When I press the back button to come back from a fragment, my activity shows a blank page.
What can I do to show the previous state of activity?
I use back stack in my project.
This is my code for pressing the back button:
public void onBackPressed()
{
if ( manager.getBackStackEntryCount() > 0 )
{
manager.popBackStack();
}
else
{
super.onBackPressed();
}
}
});
and this is for the fragment:
public void addFragmentA()
{
FragmentA a = new FragmentA();
getSupportFragmentManager().beginTransaction().replace(R.id.container, a,"fraga").addToBackStack("fraga").commit();
}
The code for the listener is:
manager.addOnBackStackChangedListener(this);
I want to work with a listener.
How can I do that?
You can use your Fragments View to move to any other Fragment or Activity.
In your Fragment.xml -> onCreateView() method
view.requestFocus();
view.setFocusableInTouchMode(true);
view.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if( keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
//Write you code here to go back to any activity or fragment
return true;
}
return false;
}
});

close fullscreen of Youtube Player on back button inside fragment

I am using Master/Detail layout in a tablet, on the left few buttons to open several fragments, one of the fragments contains youtube player.
The Problem,
When the youtube player is full screen, and i press back button, The activity onBackPressed is called, and the whole activity is closed.
What i have tried,
1- Added on KeyListener for parent fragment (which contains the Youtube Fragment) and handle when click on back button, but this listener is called only if the player is not fullscreen, otherwise it is not called,
rootView.setFocusableInTouchMode(true);
rootView.requestFocus();
rootView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
try {
// Close full screen
return true;
} catch (Exception e) {
AHHExceptionHandler.handleException(e);
}
}
return false;
}
});
2- Added onKeyListener to youtubeFragment View to check if it is full screen then close the full screen mode
youTubeFragment.getView().setFocusableInTouchMode(true);
youTubeFragment.getView().requestFocus();
youTubeFragment.getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
try {
youTubePlayer.setFullscreen(false);
return true;
} catch (Exception e) {
AHHExceptionHandler.handleException(e);
}
}
return false;
}
});
And this is also not called in all cases.
I need to handle the hardware back button while the youtube player is in fullscreen, the fullscreen mode is closed and the application is in its previous state.
Thanks.
Edit 1:
- I want to handle this inside the fragment, instead of handling it in the parent Activity, I already handling it inside the parent activity, but I don't like this solution.
Just to add to Andre's reply.
In your parent Activity add:
public YouTubePlayer youTubePlayer;
public boolean isYouTubePlayerFullScreen;
In your fragment add:
MainActivity mainActivity = (MainActivity) getActivity();
Then, on YouTubePlayerFragment initialization:
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean b) {
mainActivity.youTubePlayer = player;
player.loadVideo(videoId);
player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
mainActivity.isYouTubePlayerFullScreen = b;
}
});
}
Now your Activity has access to YouTubePlayer and information if player is full screen or not.
Next, inside your Activity, override onBackPressed like this:
#Override
public void onBackPressed() {
if (youTubePlayer != null && isYouTubePlayerFullScreen){
youTubePlayer.setFullscreen(false);
} else {
super.onBackPressed();
}
}
You can override onBackPressed() in your activity and in case your player is in fullscreen, you can handle it there as follows:
#Override
public void onBackPressed() {
if (youtubePlayer != null && isFullscreen) {
// if fullscreen, set fullscreen false
youtubePlayer.setFullscreen(false);
} else {
// if NOT fullscreen, perform default call on back press
super.onBackPressed();
}
}
P.S. In above code fragment, isFullscreen is instance variable of our
activity and is synced with youtubePlayer state from within
OnFullscreenListener set on youtubePlayer.setOnFullScreenListener().
Hope that makes sense :)

How to disable back button pressed for webview in android?

How to disable back button pressed for webview in android ?
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (wv1 != null && (keyCode == KeyEvent.KEYCODE_BACK)
&& wv1.canGoBack() )
{
wv1.goBack();
}
return true;
}
If you want to disable back button action when the WebView Visible and enable back button action if the WebView in not Visible try the below code in your Activity
#Override
public void onBackPressed() {
if(webview.getVisibility()==View.VISIBLE){
// dont pass back button action
if(webview.canGoBack()){
webview.goBack();
}
return;
}else{
// pass back button action
super.onBackPressed();
}
}
Simply override the onBackPressed() method.
#Override
public void onBackPressed() { }
Please try this
#Override
public void onBackPressed() {
if(webview.canGoBack()){
webview.goBack();
}
else{
super.onBackPressed();
}
}
There are many ways to make it,
Solution 1, overriding dispatchKeyEvent()
dispatchKeyEvent()(API Level 1, Android 1.0)
Refer to my answer use dispatchKeyEvent to disable back button
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
// TODO Auto-generated method stub
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.dispatchKeyEvent(event);
}
Solution 2, overriding onBackPressed()
onBackPressed() (API Level 5, Android 2.0)
Refer to Use onBackPressed() to disable back button
#Override
public void onBackPressed() {
}
Solution 3, overriding onKeyDown()
onKeyDown() (API Level 1, Android 1.0)
Refer to Use onKeyDown() to disable back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
return true;
}
return super.onKeyDown(keyCode, event);
}
You have add below code in Activity for disable activity back pressed
#Override
public void onBackPressed() {
}
Add this below code in java file :
WebView mwebView;
Button backButton1;
backButton1 = findViewById(R.id.backButton1);
mwebView = findViewById(R.id.mwebView);
backButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mWebView.destroy();
}
});

Disable Back Button press from fragment

My application has an activity with so many fragments. I want to disable the back button press in some fragment. I tried with the below code. But it doesn't work.
In the main activity:
#Override
public void onBackPressed() {
super.onBackPressed();
OrderFragment.onBackPress();
}
In the fragment,
public static void onBackPressed()
{
Log.d(TAG,"It listen");
}
I have the log message but, how can I disable the back button from my fragment.
You should keep a reference to the fragment you want to disable/handle back press event on your main activity:
class MainActivity{
OrderFragment mOrderFragment;
#Override
public void onBackPressed() {
if(mOrderFragment.isVisible())
mOrderFragment.onBackPressed();
else
super.onBackPressed();
}
}
In OrderFragment:
public void onBackPressed() {
//handle back press event
}
In your oncreateView() method you need to write this code and in KEYCODE_BACk return should true then it will stop the back button option for particular fragment
View v = inflater.inflate(R.layout.xyz, container, false);
//Back pressed Logic for fragment
v.setFocusableInTouchMode(true);
v.requestFocus();
v.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
}
return false;
}
});
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if( keyCode == KeyEvent.KEYCODE_BACK ) {
// leave this blank in order to disable the back press
return true;
} else {
return false;
}
}
});
I think you have to Override onResume method in fragments which you need to disable the back press.Tryout the following code.
#Override
public void onResume() {
super.onResume();
this.getView().setFocusableInTouchMode(true);
this.getView().requestFocus();
this.getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return false;
}
});
}
Have you tried like this, Actually it works for me before.
you can set listener for Back key. if you add it, i guess it works.
youfragment.getView().setOnKeyListener( new OnKeyListener()
{
#Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
return true;
}
return false;
}
}
);
super.onBackPressed in the activity is the default implementation. Remove this if you don't want it.
I know this is an old question and because of navigation components and new ways this situation rarely occurs, still, maybe my answer helps someone.
I came across a similar situation where I needed the back button to be disabled and I couldn't change the activity as well. So in a fragment, I added this code block.
Language: Kotlin
override fun onResume() {
super.onResume()
this.requireView().isFocusableInTouchMode = true
this.requireView().requestFocus()
this.requireView().setOnKeyListener { _, keyCode, _ ->
keyCode == KeyEvent.KEYCODE_BACK
}
}
This will disable your back press on that specific fragment
#Override
public void onBackPressed() {
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (currentFragment instanceof YourFragment) {
currentFragment.onBackPressed();
} else
super.onBackPressed();
}
override fun onBackPressed() {
val currentFragment = findNavController(R.id.nav_host_fragment).currentDestination?.id
if (currentFragment == R.id.YourFragment) {
return
}
super.onBackPressed()
If you don't want your fragment to be in the backstack you can do so, by not adding it to the backstack in the transaction. So do NOT call FragmentTransaction.addToBackStack(); on the fragments you do not want in your backstack.
onBackPressed works like this:
public void More onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}
}
Thus when you call super.onBackPressed() you pop the BackStack before finishing the activity. The best way to sort this out is to make sure you do not add the fragments to the BackStack. It is normally done like this:
fragmentTransaction.addToBackStack(TAG);
An alternative solution, but uglier since you have still useless code left, would be making onBackPressed() directly call finish() to end the activity.
I would strongly advise you not use getView().setOnKeyListener(...) since it is code smell.
Try this
public void onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}else{
super.onBackPressed();}
}

How can I close my application on back pressed

I want to close application when I press device's back button.I am using this code..
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
this.finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
Override the onBackPressed() in your Activity where you want application to Quit when the device back button clicked
#Override
public void onBackPressed() {
android.os.Process.killProcess(android.os.Process.myPid());
}
This code does it :
public void onPause() {
super.onPause();
finish();
}
Don't forget to mark it as answer if it helped ;)
The answer that you marked as correct will stop the app every onPause of this activity, which is not an event of the back button cick, the right answer is :
#Override
public void onBackPressed() {
finish();
}

Categories

Resources