refactor onBackPressed to use the callback dispatcher (#937)

This commit is contained in:
m2049r 2024-04-05 15:57:37 +02:00 committed by GitHub
parent cd6f646b63
commit 451371cd92
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 104 additions and 111 deletions

View File

@ -17,11 +17,14 @@
package com.m2049r.xmrwallet; package com.m2049r.xmrwallet;
import android.content.Context; import android.content.Context;
import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.os.PowerManager; import android.os.PowerManager;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.CallSuper; import androidx.annotation.CallSuper;
import androidx.fragment.app.FragmentActivity;
import com.m2049r.xmrwallet.data.BarcodeData; import com.m2049r.xmrwallet.data.BarcodeData;
import com.m2049r.xmrwallet.dialog.ProgressDialog; import com.m2049r.xmrwallet.dialog.ProgressDialog;
@ -35,18 +38,13 @@ public class BaseActivity extends SecureActivity
ProgressDialog progressDialog = null; ProgressDialog progressDialog = null;
private class SimpleProgressDialog extends ProgressDialog { private static class SimpleProgressDialog extends ProgressDialog {
SimpleProgressDialog(Context context, int msgId) { SimpleProgressDialog(Context context, int msgId) {
super(context); super(context);
setCancelable(false); setCancelable(false);
setMessage(context.getString(msgId)); setMessage(context.getString(msgId));
} }
@Override
public void onBackPressed() {
// prevent back button
}
} }
@Override @Override
@ -59,13 +57,15 @@ public class BaseActivity extends SecureActivity
progressDialog = new SimpleProgressDialog(BaseActivity.this, msgId); progressDialog = new SimpleProgressDialog(BaseActivity.this, msgId);
if (delayMillis > 0) { if (delayMillis > 0) {
Handler handler = new Handler(); Handler handler = new Handler();
handler.postDelayed(new Runnable() { handler.postDelayed(() -> {
public void run() { if (progressDialog != null) {
if (progressDialog != null) progressDialog.show(); progressDialog.show();
disableBackPressed();
} }
}, delayMillis); }, delayMillis);
} else { } else {
progressDialog.show(); progressDialog.show();
disableBackPressed();
} }
} }
@ -75,6 +75,7 @@ public class BaseActivity extends SecureActivity
progressDialog = new LedgerProgressDialog(BaseActivity.this, mode); progressDialog = new LedgerProgressDialog(BaseActivity.this, mode);
Ledger.setListener((Ledger.Listener) progressDialog); Ledger.setListener((Ledger.Listener) progressDialog);
progressDialog.show(); progressDialog.show();
disableBackPressed();
} }
@Override @Override
@ -87,6 +88,28 @@ public class BaseActivity extends SecureActivity
progressDialog.dismiss(); progressDialog.dismiss();
} }
progressDialog = null; progressDialog = null;
enableBackPressed();
}
OnBackPressedCallback backPressedCallback = new OnBackPressedCallback(false) {
@Override
public void handleOnBackPressed() {
// no going back
}
};
public void disableBackPressed() {
backPressedCallback.setEnabled(true);
}
public void enableBackPressed() {
backPressedCallback.setEnabled(false);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getOnBackPressedDispatcher().addCallback(this, backPressedCallback);
} }
static final int RELEASE_WAKE_LOCK_DELAY = 5000; // millisconds static final int RELEASE_WAKE_LOCK_DELAY = 5000; // millisconds

View File

@ -40,6 +40,7 @@ import android.widget.ScrollView;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
@ -98,6 +99,13 @@ public class GenerateReviewFragment extends Fragment {
private String walletPath; private String walletPath;
private String walletName; private String walletName;
private OnBackPressedCallback backPressedCallback = new OnBackPressedCallback(false) {
@Override
public void handleOnBackPressed() {
// nothing
}
};
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
@ -160,6 +168,9 @@ public class GenerateReviewFragment extends Fragment {
walletPath = args.getString(REQUEST_PATH); walletPath = args.getString(REQUEST_PATH);
localPassword = args.getString(REQUEST_PASSWORD); localPassword = args.getString(REQUEST_PASSWORD);
showDetails(); showDetails();
if (type.equals(GenerateReviewFragment.VIEW_TYPE_ACCEPT)) {
backPressedCallback.setEnabled(true);
}
return view; return view;
} }
@ -420,14 +431,11 @@ public class GenerateReviewFragment extends Fragment {
pbProgress.setVisibility(View.INVISIBLE); pbProgress.setVisibility(View.INVISIBLE);
} }
boolean backOk() {
return !type.equals(GenerateReviewFragment.VIEW_TYPE_ACCEPT);
}
@Override @Override
public void onCreate(@Nullable Bundle savedInstanceState) { public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setHasOptionsMenu(true); setHasOptionsMenu(true);
requireActivity().getOnBackPressedDispatcher().addCallback(this, backPressedCallback);
} }
@Override @Override

View File

@ -295,7 +295,7 @@ public class LoginActivity extends BaseActivity
toolbar.setOnButtonListener(type -> { toolbar.setOnButtonListener(type -> {
switch (type) { switch (type) {
case Toolbar.BUTTON_BACK: case Toolbar.BUTTON_BACK:
onBackPressed(); getOnBackPressedDispatcher().onBackPressed();
break; break;
case Toolbar.BUTTON_CLOSE: case Toolbar.BUTTON_CLOSE:
finish(); finish();
@ -1086,30 +1086,6 @@ public class LoginActivity extends BaseActivity
} }
} }
@Override
public void onBackPressed() {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (f instanceof GenerateReviewFragment) {
if (((GenerateReviewFragment) f).backOk()) {
super.onBackPressed();
}
} else if (f instanceof NodeFragment) {
if (!((NodeFragment) f).isRefreshing()) {
super.onBackPressed();
} else {
Toast.makeText(LoginActivity.this, getString(R.string.node_refresh_wait), Toast.LENGTH_LONG).show();
}
} else if (f instanceof LoginFragment) {
if (((LoginFragment) f).isFabOpen()) {
((LoginFragment) f).animateFAB();
} else {
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
final int id = item.getItemId(); final int id = item.getItemId();
@ -1294,21 +1270,21 @@ public class LoginActivity extends BaseActivity
if (!Ledger.check()) { if (!Ledger.check()) {
Ledger.disconnect(); Ledger.disconnect();
runOnUiThread(() -> Toast.makeText(LoginActivity.this, runOnUiThread(() -> Toast.makeText(LoginActivity.this,
getString(R.string.toast_ledger_start_app, usbDevice.getProductName()), getString(R.string.toast_ledger_start_app, usbDevice.getProductName()),
Toast.LENGTH_SHORT) Toast.LENGTH_SHORT)
.show()); .show());
} else { } else {
registerDetachReceiver(); registerDetachReceiver();
onLedgerAction(); onLedgerAction();
runOnUiThread(() -> Toast.makeText(LoginActivity.this, runOnUiThread(() -> Toast.makeText(LoginActivity.this,
getString(R.string.toast_ledger_attached, usbDevice.getProductName()), getString(R.string.toast_ledger_attached, usbDevice.getProductName()),
Toast.LENGTH_SHORT) Toast.LENGTH_SHORT)
.show()); .show());
} }
} catch (IOException ex) { } catch (IOException ex) {
runOnUiThread(() -> Toast.makeText(LoginActivity.this, runOnUiThread(() -> Toast.makeText(LoginActivity.this,
getString(R.string.open_wallet_ledger_missing), getString(R.string.open_wallet_ledger_missing),
Toast.LENGTH_SHORT) Toast.LENGTH_SHORT)
.show()); .show());
} }
} }
@ -1368,8 +1344,8 @@ public class LoginActivity extends BaseActivity
Timber.i("Ledger detached!"); Timber.i("Ledger detached!");
if (device != null) if (device != null)
runOnUiThread(() -> Toast.makeText(LoginActivity.this, runOnUiThread(() -> Toast.makeText(LoginActivity.this,
getString(R.string.toast_ledger_detached, device.getProductName()), getString(R.string.toast_ledger_detached, device.getProductName()),
Toast.LENGTH_SHORT) Toast.LENGTH_SHORT)
.show()); .show());
Ledger.disconnect(); Ledger.disconnect();
onLedgerAction(); onLedgerAction();
@ -1383,7 +1359,7 @@ public class LoginActivity extends BaseActivity
public void onLedgerAction() { public void onLedgerAction() {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container); Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (f instanceof GenerateFragment) { if (f instanceof GenerateFragment) {
onBackPressed(); getOnBackPressedDispatcher().onBackPressed();
} else if (f instanceof LoginFragment) { } else if (f instanceof LoginFragment) {
if (((LoginFragment) f).isFabOpen()) { if (((LoginFragment) f).isFabOpen()) {
((LoginFragment) f).animateFAB(); ((LoginFragment) f).animateFAB();

View File

@ -35,6 +35,7 @@ import android.widget.RelativeLayout;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
@ -148,6 +149,13 @@ public class LoginFragment extends Fragment implements WalletInfoAdapter.OnInter
//activityCallback.runOnNetCipher(this::pingSelectedNode); //activityCallback.runOnNetCipher(this::pingSelectedNode);
} }
private OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(false) {
@Override
public void handleOnBackPressed() {
animateFAB();
}
};
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
@ -287,6 +295,7 @@ public class LoginFragment extends Fragment implements WalletInfoAdapter.OnInter
public void onCreate(@Nullable Bundle savedInstanceState) { public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setHasOptionsMenu(true); setHasOptionsMenu(true);
requireActivity().getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
} }
@Override @Override
@ -295,7 +304,7 @@ public class LoginFragment extends Fragment implements WalletInfoAdapter.OnInter
super.onCreateOptionsMenu(menu, inflater); super.onCreateOptionsMenu(menu, inflater);
} }
private boolean isFabOpen = false; private boolean fabOpen = false;
private FloatingActionButton fab, fabNew, fabView, fabKey, fabSeed, fabImport, fabLedger; private FloatingActionButton fab, fabNew, fabView, fabKey, fabSeed, fabImport, fabLedger;
private RelativeLayout fabScreen; private RelativeLayout fabScreen;
private RelativeLayout fabNewL, fabViewL, fabKeyL, fabSeedL, fabImportL, fabLedgerL; private RelativeLayout fabNewL, fabViewL, fabKeyL, fabSeedL, fabImportL, fabLedgerL;
@ -303,11 +312,16 @@ public class LoginFragment extends Fragment implements WalletInfoAdapter.OnInter
private Animation fab_pulse; private Animation fab_pulse;
public boolean isFabOpen() { public boolean isFabOpen() {
return isFabOpen; return fabOpen;
}
private void setFabOpen(boolean value) {
fabOpen = value;
onBackPressedCallback.setEnabled(value);
} }
public void animateFAB() { public void animateFAB() {
if (isFabOpen) { // close the fab if (isFabOpen()) { // close the fab
fabScreen.setClickable(false); fabScreen.setClickable(false);
fabScreen.startAnimation(fab_close_screen); fabScreen.startAnimation(fab_close_screen);
fab.startAnimation(rotate_backward); fab.startAnimation(rotate_backward);
@ -326,7 +340,7 @@ public class LoginFragment extends Fragment implements WalletInfoAdapter.OnInter
fabImportL.startAnimation(fab_close); fabImportL.startAnimation(fab_close);
fabImport.setClickable(false); fabImport.setClickable(false);
} }
isFabOpen = false; setFabOpen(false);
} else { // open the fab } else { // open the fab
fabScreen.setClickable(true); fabScreen.setClickable(true);
fabScreen.startAnimation(fab_open_screen); fabScreen.startAnimation(fab_open_screen);
@ -360,7 +374,7 @@ public class LoginFragment extends Fragment implements WalletInfoAdapter.OnInter
fabImportL.startAnimation(fab_open); fabImportL.startAnimation(fab_open);
fabImport.setClickable(true); fabImport.setClickable(true);
} }
isFabOpen = true; setFabOpen(true);
} }
} }
@ -372,7 +386,7 @@ public class LoginFragment extends Fragment implements WalletInfoAdapter.OnInter
animateFAB(); animateFAB();
} else if (id == R.id.fabNew) { } else if (id == R.id.fabNew) {
fabScreen.setVisibility(View.INVISIBLE); fabScreen.setVisibility(View.INVISIBLE);
isFabOpen = false; setFabOpen(false);
activityCallback.onAddWallet(GenerateFragment.TYPE_NEW); activityCallback.onAddWallet(GenerateFragment.TYPE_NEW);
} else if (id == R.id.fabView) { } else if (id == R.id.fabView) {
animateFAB(); animateFAB();

View File

@ -31,6 +31,7 @@ import android.widget.Button;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
@ -145,6 +146,13 @@ public class NodeFragment extends Fragment
} }
} }
private OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(false) {
@Override
public void handleOnBackPressed() {
Toast.makeText(requireActivity(), getString(R.string.node_refresh_wait), Toast.LENGTH_LONG).show();
}
};
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
@ -187,6 +195,7 @@ public class NodeFragment extends Fragment
private boolean refresh(int type) { private boolean refresh(int type) {
if (asyncFindNodes != null) return false; // ignore refresh request as one is ongoing if (asyncFindNodes != null) return false; // ignore refresh request as one is ongoing
onBackPressedCallback.setEnabled(true);
asyncFindNodes = new AsyncFindNodes(); asyncFindNodes = new AsyncFindNodes();
updateRefreshElements(); updateRefreshElements();
asyncFindNodes.execute(type); asyncFindNodes.execute(type);
@ -197,6 +206,7 @@ public class NodeFragment extends Fragment
public void onCreate(@Nullable Bundle savedInstanceState) { public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setHasOptionsMenu(true); setHasOptionsMenu(true);
requireActivity().getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
} }
@Override @Override
@ -342,6 +352,7 @@ public class NodeFragment extends Fragment
private void complete() { private void complete() {
asyncFindNodes = null; asyncFindNodes = null;
onBackPressedCallback.setEnabled(false);
if (!isAdded()) return; if (!isAdded()) return;
//if (isCancelled()) return; //if (isCancelled()) return;
tvPull.setText(getString(R.string.node_pull_hint)); tvPull.setText(getString(R.string.node_pull_hint));
@ -575,6 +586,7 @@ public class NodeFragment extends Fragment
} }
} }
} }
} }
void restoreDefaultNodes() { void restoreDefaultNodes() {

View File

@ -1,21 +0,0 @@
/*
* Copyright (c) 2017 m2049r
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.m2049r.xmrwallet;
public interface OnBackPressedListener {
boolean onBackPressed();
}

View File

@ -377,12 +377,12 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste
switch (type) { switch (type) {
case Toolbar.BUTTON_BACK: case Toolbar.BUTTON_BACK:
onDisposeRequest(); onDisposeRequest();
onBackPressed(); getOnBackPressedDispatcher().onBackPressed();
break; break;
case Toolbar.BUTTON_CANCEL: case Toolbar.BUTTON_CANCEL:
onDisposeRequest(); onDisposeRequest();
Helper.hideKeyboard(WalletActivity.this); Helper.hideKeyboard(WalletActivity.this);
WalletActivity.super.onBackPressed(); getOnBackPressedDispatcher().onBackPressed();
break; break;
case Toolbar.BUTTON_CLOSE: case Toolbar.BUTTON_CLOSE:
finish(); finish();
@ -964,23 +964,6 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste
return getWallet().getUnlockedBalance(); return getWallet().getUnlockedBalance();
} }
@Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
return;
}
final Fragment fragment = getCurrentFragment();
if (fragment instanceof OnBackPressedListener) {
if (!((OnBackPressedListener) fragment).onBackPressed()) {
super.onBackPressed();
}
} else {
super.onBackPressed();
}
Helper.hideKeyboard(this);
}
@Override @Override
public void onFragmentDone() { public void onFragmentDone() {
popFragmentStack(null); popFragmentStack(null);
@ -1201,7 +1184,7 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste
@Override @Override
public void onSubaddressSelected(@Nullable final Subaddress subaddress) { public void onSubaddressSelected(@Nullable final Subaddress subaddress) {
selectedSubaddressIndex = subaddress.getAddressIndex(); selectedSubaddressIndex = subaddress.getAddressIndex();
onBackPressed(); getOnBackPressedDispatcher().onBackPressed();
} }
@Override @Override

View File

@ -29,6 +29,7 @@ import android.view.ViewGroup;
import android.widget.Button; import android.widget.Button;
import android.widget.EditText; import android.widget.EditText;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
@ -37,7 +38,6 @@ import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager; import androidx.viewpager.widget.ViewPager;
import com.google.android.material.transition.MaterialContainerTransform; import com.google.android.material.transition.MaterialContainerTransform;
import com.m2049r.xmrwallet.OnBackPressedListener;
import com.m2049r.xmrwallet.OnUriScannedListener; import com.m2049r.xmrwallet.OnUriScannedListener;
import com.m2049r.xmrwallet.R; import com.m2049r.xmrwallet.R;
import com.m2049r.xmrwallet.WalletActivity; import com.m2049r.xmrwallet.WalletActivity;
@ -63,7 +63,7 @@ public class SendFragment extends Fragment
SendAmountWizardFragment.Listener, SendAmountWizardFragment.Listener,
SendConfirmWizardFragment.Listener, SendConfirmWizardFragment.Listener,
SendSuccessWizardFragment.Listener, SendSuccessWizardFragment.Listener,
OnBackPressedListener, OnUriScannedListener { OnUriScannedListener {
final static public int MIXIN = 0; final static public int MIXIN = 0;
@ -248,16 +248,18 @@ public class SendFragment extends Fragment
private SpendViewPager spendViewPager; private SpendViewPager spendViewPager;
private SpendPagerAdapter pagerAdapter; private SpendPagerAdapter pagerAdapter;
@Override OnBackPressedCallback backPressedCallback = new OnBackPressedCallback(true) {
public boolean onBackPressed() { @Override
if (isComitted()) return true; // no going back public void handleOnBackPressed() {
if (spendViewPager.getCurrentItem() == 0) { if (isComitted()) return; // no going back
return false; if (spendViewPager.getCurrentItem() == 0) {
} else { setEnabled(false);
spendViewPager.previous(); requireActivity().getOnBackPressedDispatcher().onBackPressed();
return true; } else {
spendViewPager.previous();
}
} }
} };
@Override @Override
public boolean onUriScanned(BarcodeData barcodeData) { public boolean onUriScanned(BarcodeData barcodeData) {
@ -546,8 +548,9 @@ public class SendFragment extends Fragment
final MaterialContainerTransform transform = new MaterialContainerTransform(); final MaterialContainerTransform transform = new MaterialContainerTransform();
transform.setDrawingViewId(R.id.fragment_container); transform.setDrawingViewId(R.id.fragment_container);
transform.setDuration(getResources().getInteger(R.integer.tx_item_transition_duration)); transform.setDuration(getResources().getInteger(R.integer.tx_item_transition_duration));
transform.setAllContainerColors(ThemeHelper.getThemedColor(getContext(), android.R.attr.colorBackground)); transform.setAllContainerColors(ThemeHelper.getThemedColor(requireContext(), android.R.attr.colorBackground));
setSharedElementEnterTransition(transform); setSharedElementEnterTransition(transform);
requireActivity().getOnBackPressedDispatcher().addCallback(this, backPressedCallback);
} }
@Override @Override

View File

@ -46,11 +46,6 @@ public class LedgerProgressDialog extends ProgressDialog implements Ledger.Liste
setMessage(context.getString(R.string.progress_ledger_progress)); setMessage(context.getString(R.string.progress_ledger_progress));
} }
@Override
public void onBackPressed() {
// prevent back button
}
private int firstSubaddress = Integer.MAX_VALUE; private int firstSubaddress = Integer.MAX_VALUE;
private boolean validate = false; private boolean validate = false;