Overhaul Theming System (Dark Mode Support) (#2443)

* refactor launcher background color
* Remove redundant attrs
* Fix input view alignment
* Standardized typography and optimized them to enable theme overlays
* Utilize colorPrimary
* Apply theme color values to views
* Fix misplaced separators
* Add theming documentation
* Refactor bottom navigation view
* Add custom color references
* Update naming and docs
* Apply new theme to wallet connect ui
* Update wallet connect session detail to match Zeplin spec
* Adjust wallet connect dialog title style
* Updated buttons to become round
* Changed copytextview background color
pull/2464/head
justindg 3 years ago committed by GitHub
parent 01897c9acc
commit cb03caf3e2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 3
      app/build.gradle
  2. 2
      app/src/analytics/java/com/alphawallet/app/util/RateApp.java
  3. 13
      app/src/debug/AndroidManifest.xml
  4. 84
      app/src/main/AndroidManifest.xml
  5. BIN
      app/src/main/ic_launcher-playstore.png
  6. 59
      app/src/main/java/com/alphawallet/app/App.java
  7. 6
      app/src/main/java/com/alphawallet/app/C.java
  8. 6
      app/src/main/java/com/alphawallet/app/entity/Transaction.java
  9. 2
      app/src/main/java/com/alphawallet/app/repository/EthereumNetworkBase.java
  10. 3
      app/src/main/java/com/alphawallet/app/repository/PreferenceRepositoryType.java
  11. 13
      app/src/main/java/com/alphawallet/app/repository/SharedPreferenceRepository.java
  12. 15
      app/src/main/java/com/alphawallet/app/router/HelpRouter.java
  13. 4
      app/src/main/java/com/alphawallet/app/service/NotificationService.java
  14. 91
      app/src/main/java/com/alphawallet/app/ui/AddCustomRPCNetworkActivity.java
  15. 2
      app/src/main/java/com/alphawallet/app/ui/AddEthereumChainPrompt.java
  16. 4
      app/src/main/java/com/alphawallet/app/ui/AddTokenActivity.java
  17. 167
      app/src/main/java/com/alphawallet/app/ui/AdvancedSettingsActivity.java
  18. 333
      app/src/main/java/com/alphawallet/app/ui/BackupKeyActivity.java
  19. 2
      app/src/main/java/com/alphawallet/app/ui/BaseActivity.java
  20. 4
      app/src/main/java/com/alphawallet/app/ui/DappBrowserFragment.java
  21. 4
      app/src/main/java/com/alphawallet/app/ui/Erc20DetailActivity.java
  22. 4
      app/src/main/java/com/alphawallet/app/ui/FunctionActivity.java
  23. 79
      app/src/main/java/com/alphawallet/app/ui/GasSettingsActivity.java
  24. 188
      app/src/main/java/com/alphawallet/app/ui/HelpActivity.java
  25. 125
      app/src/main/java/com/alphawallet/app/ui/HomeActivity.java
  26. 6
      app/src/main/java/com/alphawallet/app/ui/ImportSeedFragment.java
  27. 2
      app/src/main/java/com/alphawallet/app/ui/ImportWalletActivity.java
  28. 12
      app/src/main/java/com/alphawallet/app/ui/MyAddressActivity.java
  29. 3
      app/src/main/java/com/alphawallet/app/ui/NFTAssetsFragment.java
  30. 257
      app/src/main/java/com/alphawallet/app/ui/NewSettingsFragment.java
  31. 10
      app/src/main/java/com/alphawallet/app/ui/RedeemAssetSelectActivity.java
  32. 31
      app/src/main/java/com/alphawallet/app/ui/SearchFragment.java
  33. 121
      app/src/main/java/com/alphawallet/app/ui/SelectCurrencyActivity.java
  34. 82
      app/src/main/java/com/alphawallet/app/ui/SelectLocaleActivity.java
  35. 24
      app/src/main/java/com/alphawallet/app/ui/SelectNetworkBaseActivity.java
  36. 2
      app/src/main/java/com/alphawallet/app/ui/SelectNetworkFilterActivity.java
  37. 79
      app/src/main/java/com/alphawallet/app/ui/SelectThemeActivity.java
  38. 1
      app/src/main/java/com/alphawallet/app/ui/SellDetailActivity.java
  39. 2
      app/src/main/java/com/alphawallet/app/ui/SendActivity.java
  40. 6
      app/src/main/java/com/alphawallet/app/ui/SetWatchWalletFragment.java
  41. 7
      app/src/main/java/com/alphawallet/app/ui/TokenActivity.java
  42. 21
      app/src/main/java/com/alphawallet/app/ui/TokenAlertsFragment.java
  43. 2
      app/src/main/java/com/alphawallet/app/ui/TokenDetailActivity.java
  44. 2
      app/src/main/java/com/alphawallet/app/ui/TokenFunctionActivity.java
  45. 1
      app/src/main/java/com/alphawallet/app/ui/TransferTicketDetailActivity.java
  46. 2
      app/src/main/java/com/alphawallet/app/ui/WalletActionsActivity.java
  47. 4
      app/src/main/java/com/alphawallet/app/ui/WalletConnectActivity.java
  48. 180
      app/src/main/java/com/alphawallet/app/ui/WalletFragment.java
  49. 5
      app/src/main/java/com/alphawallet/app/ui/WalletsActivity.java
  50. 2
      app/src/main/java/com/alphawallet/app/ui/widget/adapter/ActivityAdapter.java
  51. 2
      app/src/main/java/com/alphawallet/app/ui/widget/adapter/DappBrowserSuggestionsAdapter.java
  52. 7
      app/src/main/java/com/alphawallet/app/ui/widget/adapter/MultiSelectNetworkAdapter.java
  53. 20
      app/src/main/java/com/alphawallet/app/ui/widget/adapter/SingleSelectNetworkAdapter.java
  54. 5
      app/src/main/java/com/alphawallet/app/ui/widget/adapter/SuggestionsAdapter.java
  55. 188
      app/src/main/java/com/alphawallet/app/ui/widget/adapter/WalletsAdapter.java
  56. 2
      app/src/main/java/com/alphawallet/app/ui/widget/adapter/WalletsSummaryAdapter.java
  57. 87
      app/src/main/java/com/alphawallet/app/ui/widget/entity/HistoryChart.java
  58. 2
      app/src/main/java/com/alphawallet/app/ui/widget/entity/NumericInput.java
  59. 3
      app/src/main/java/com/alphawallet/app/ui/widget/holder/AssetInstanceScriptHolder.java
  60. 12
      app/src/main/java/com/alphawallet/app/ui/widget/holder/ChainNameHeaderHolder.java
  61. 6
      app/src/main/java/com/alphawallet/app/ui/widget/holder/EventHolder.java
  62. 2
      app/src/main/java/com/alphawallet/app/ui/widget/holder/NFTAssetHolder.java
  63. 12
      app/src/main/java/com/alphawallet/app/ui/widget/holder/TextHolder.java
  64. 47
      app/src/main/java/com/alphawallet/app/ui/widget/holder/TokenHolder.java
  65. 8
      app/src/main/java/com/alphawallet/app/ui/widget/holder/TransactionDateHolder.java
  66. 7
      app/src/main/java/com/alphawallet/app/ui/widget/holder/TransactionHolder.java
  67. 1
      app/src/main/java/com/alphawallet/app/ui/widget/holder/TransferHolder.java
  68. 12
      app/src/main/java/com/alphawallet/app/ui/widget/holder/WalletHolder.java
  69. 2
      app/src/main/java/com/alphawallet/app/ui/widget/holder/WalletSummaryHeaderHolder.java
  70. 15
      app/src/main/java/com/alphawallet/app/ui/widget/holder/WalletSummaryHolder.java
  71. 29
      app/src/main/java/com/alphawallet/app/ui/widget/holder/WarningHolder.java
  72. 55
      app/src/main/java/com/alphawallet/app/util/TabUtils.java
  73. 9
      app/src/main/java/com/alphawallet/app/util/Utils.java
  74. 39
      app/src/main/java/com/alphawallet/app/viewmodel/AdvancedSettingsViewModel.java
  75. 7
      app/src/main/java/com/alphawallet/app/viewmodel/HomeViewModel.java
  76. 53
      app/src/main/java/com/alphawallet/app/viewmodel/NewSettingsViewModel.java
  77. 64
      app/src/main/java/com/alphawallet/app/viewmodel/SelectThemeViewModel.java
  78. 2
      app/src/main/java/com/alphawallet/app/viewmodel/WalletViewModel.java
  79. 21
      app/src/main/java/com/alphawallet/app/web3/Web3TokenView.java
  80. 337
      app/src/main/java/com/alphawallet/app/web3/Web3View.java
  81. 168
      app/src/main/java/com/alphawallet/app/widget/AWalletBottomNavigationView.java
  82. 5
      app/src/main/java/com/alphawallet/app/widget/AWalletConfirmationDialog.java
  83. 4
      app/src/main/java/com/alphawallet/app/widget/ActionSheetDialog.java
  84. 2
      app/src/main/java/com/alphawallet/app/widget/ActivityHistoryList.java
  85. 3
      app/src/main/java/com/alphawallet/app/widget/CertifiedToolbarView.java
  86. 99
      app/src/main/java/com/alphawallet/app/widget/CopyTextView.java
  87. 81
      app/src/main/java/com/alphawallet/app/widget/DepositView.java
  88. 2
      app/src/main/java/com/alphawallet/app/widget/DialogInfoItem.java
  89. 67
      app/src/main/java/com/alphawallet/app/widget/FilterDialog.java
  90. 296
      app/src/main/java/com/alphawallet/app/widget/FunctionButtonBar.java
  91. 144
      app/src/main/java/com/alphawallet/app/widget/HelperTextInputLayout.java
  92. 6
      app/src/main/java/com/alphawallet/app/widget/InputAddress.java
  93. 17
      app/src/main/java/com/alphawallet/app/widget/InputAmount.java
  94. 17
      app/src/main/java/com/alphawallet/app/widget/InputFiatView.java
  95. 13
      app/src/main/java/com/alphawallet/app/widget/InputView.java
  96. 1
      app/src/main/java/com/alphawallet/app/widget/NFTImageView.java
  97. 5
      app/src/main/java/com/alphawallet/app/widget/NotificationView.java
  98. 10
      app/src/main/java/com/alphawallet/app/widget/PasswordInputView.java
  99. 2
      app/src/main/java/com/alphawallet/app/widget/ProgressView.java
  100. 92
      app/src/main/java/com/alphawallet/app/widget/SearchDialog.java
  101. Some files were not shown because too many files have changed in this diff Show More

@ -183,6 +183,9 @@ dependencies {
implementation "com.google.dagger:hilt-android:2.40.5"
annotationProcessor "com.google.dagger:hilt-compiler:2.40.5"
// WebKit - for WebView Dark Mode
implementation 'androidx.webkit:webkit:1.4.0'
//Use Leak Canary for debug builds only
//debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.7'

@ -23,7 +23,7 @@ public class RateApp {
View contentView = LayoutInflater.from(context).inflate(R.layout.layout_rate_dialog, null, false);
final RatingBar ratingBar = contentView.findViewById(R.id.rating_bar);
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(context, R.style.AWLightAlertDialog)
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(context)
.setTitle(context.getString(R.string.rate_title, context.getString(R.string.app_name)))
.setView(contentView)
.setMessage(context.getString(R.string.rate_prompt, context.getString(R.string.app_name)))

@ -7,8 +7,8 @@
<uses-permission android:name="android.permission.CAMERA" />
<!-- Allows unlocking your device and activating its screen so UI tests can succeed -->
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Allows for storing and retrieving screenshots -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
@ -22,13 +22,12 @@
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:testOnly="false"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme.NoActionBar"
>
<activity
android:name="com.alphawallet.app.ui.HomeActivity">
android:testOnly="false"
android:theme="@style/AppTheme.NoActionBar">
<activity android:name="com.alphawallet.app.ui.HomeActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

@ -20,28 +20,27 @@
android:required="false" />
<application
android:extractNativeLibs="true"
android:name=".App"
android:allowBackup="false"
android:extractNativeLibs="true"
android:hardwareAccelerated="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:requestLegacyExternalStorage="true"
android:label="@string/app_name"
android:launchMode="singleTask"
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:testOnly="false"
android:theme="@style/AppTheme.NoActionBar"
android:usesCleartextTraffic="true"
tools:replace="android:name, android:theme, android:allowBackup">
<activity
android:launchMode="singleTask"
android:name=".ui.HomeActivity"
android:theme="@style/SplashTheme"
android:label="@string/app_name"
android:exported="true"
android:windowSoftInputMode="adjustPan"
>
android:launchMode="singleTask"
android:theme="@style/AppTheme.NoActionBar.Splash"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@ -104,11 +103,13 @@
<intent-filter>
<data android:scheme="wc" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
<intent-filter android:priority="999">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
@ -143,17 +144,18 @@
android:name=".ui.WalletsActivity"
android:label="@string/title_account_list" />
<activity android:name=".ui.SplashActivity"
android:theme="@style/SplashTheme" />
<activity
android:name=".ui.SplashActivity"
android:theme="@style/AppTheme.NoActionBar.Splash" />
<service
android:name=".service.WalletConnectService"
android:enabled="true">
</service>
android:enabled="true"></service>
<activity android:name=".ui.NameThisWalletActivity"
android:windowSoftInputMode="adjustResize"
android:label="@string/name_this_wallet" />
<activity
android:name=".ui.NameThisWalletActivity"
android:label="@string/name_this_wallet"
android:windowSoftInputMode="adjustResize" />
<activity
android:name=".ui.ImportWalletActivity"
android:label="@string/title_import"
@ -210,10 +212,6 @@
android:name=".ui.TransferTicketDetailActivity"
android:label="@string/label_transfer_ticket_detail" />
<activity
android:name=".ui.HelpActivity"
android:label="@string/toolbar_header_help" />
<activity
android:name=".ui.TokenDetailActivity"
android:label="@string/token_details" />
@ -230,24 +228,6 @@
android:name=".ui.FunctionActivity"
android:label="@string/token_function" />
<!--<service android:name="AlphaWalletFirebaseMessagingService">-->
<!--<intent-filter>-->
<!--<action android:name="com.google.firebase.MESSAGING_EVENT" />-->
<!--</intent-filter>-->
<!--</service>-->
<!--<meta-data-->
<!--android:name="preloaded_fonts"-->
<!--android:resource="@array/preloaded_fonts" />-->
<!--<meta-data-->
<!--android:name="com.google.firebase.messaging.default_notification_icon"-->
<!--android:resource="@mipmap/ic_alpha" />-->
<!--<meta-data-->
<!--android:name="com.google.firebase.messaging.default_notification_color"-->
<!--android:resource="@color/colorAccent" />-->
<activity
android:name=".ui.WalletActionsActivity"
android:label="Wallet Actions" />
@ -278,8 +258,8 @@
<activity
android:name=".ui.ScammerWarningActivity"
android:noHistory="true"
android:label="Scammer Warning" />
android:label="Scammer Warning"
android:noHistory="true" />
<activity
android:name=".ui.BackupKeyActivity"
@ -297,16 +277,18 @@
android:name=".ui.StaticViewer"
android:label="View Text" />
<activity android:name=".ui.TokenScriptManagementActivity"
android:label="@string/tokenscript_management"/>
<activity
android:name=".ui.TokenScriptManagementActivity"
android:label="@string/tokenscript_management" />
<activity android:name=".ui.TokenActivity"
android:label="@string/activity_label"/>
<activity
android:name=".ui.TokenActivity"
android:label="@string/activity_label" />
<activity
android:name=".ui.WalletConnectActivity"
android:launchMode="singleTop"
android:label="WalletConnect" />
android:label="WalletConnect"
android:launchMode="singleTop" />
<activity
android:name=".ui.BackupFlowActivity"
@ -327,11 +309,11 @@
<activity
android:name=".ui.SetPriceAlertActivity"
android:label="Set New Alert"
android:windowSoftInputMode="adjustResize"/>
android:windowSoftInputMode="adjustResize" />
<activity
android:name=".ui.AddCustomRPCNetworkActivity"
android:label="@string/title_activity_add_custom_rpcnetwork"/>
android:label="@string/title_activity_add_custom_rpcnetwork" />
<activity
android:name=".ui.NFTActivity"
@ -353,6 +335,10 @@
android:name=".ui.TransferNFTActivity"
android:label="NFT Transfer" />
<activity
android:name=".ui.SelectThemeActivity"
android:label="Select Mode" />
<activity
android:name=".ui.QRScanning.QRScanner"
android:label="@string/qr_scanner" />
@ -361,8 +347,8 @@
android:name=".service.PriceAlertsService"
android:enabled="true"
android:exported="false"
android:stopWithTask="true"/>
android:stopWithTask="true" />
</application>
</manifest>

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

@ -1,6 +1,14 @@
package com.alphawallet.app;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;
import android.app.Application;
import android.app.UiModeManager;
import android.content.Context;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.preference.PreferenceManager;
import com.alphawallet.app.util.ReleaseTree;
@ -9,22 +17,51 @@ import io.realm.Realm;
import timber.log.Timber;
@HiltAndroidApp
public class App extends Application {
public class App extends Application
{
@Override
public void onCreate() {
super.onCreate();
@Override
public void onCreate()
{
super.onCreate();
Realm.init(this);
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
} else {
Timber.plant(new ReleaseTree());
}
if (BuildConfig.DEBUG)
{
Timber.plant(new Timber.DebugTree());
}
else
{
Timber.plant(new ReleaseTree());
}
int defaultTheme = PreferenceManager.getDefaultSharedPreferences(this).getInt("theme", C.THEME_AUTO);
if (defaultTheme == C.THEME_LIGHT)
{
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO);
}
else if (defaultTheme == C.THEME_DARK)
{
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
}
else
{
UiModeManager uiModeManager = (UiModeManager) getSystemService(Context.UI_MODE_SERVICE);
int mode = uiModeManager.getNightMode();
if (mode == UiModeManager.MODE_NIGHT_YES)
{
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
}
else if (mode == UiModeManager.MODE_NIGHT_NO)
{
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO);
}
}
// enable pin code for the application
// enable pin code for the application
// LockManager<CustomPinActivity> lockManager = LockManager.getInstance();
// lockManager.enableAppLock(this, CustomPinActivity.class);
// lockManager.getAppLock().setShouldShowForgot(false);
}
}
}

@ -265,4 +265,10 @@ public abstract class C {
public static final String APP_NAME = "PACKAGE_NAME";
public static final String ALPHAWALLET_LOGO_URI = "https://alphawallet.com/wp-content/themes/alphawallet/img/alphawallet-logo.svg";
// Theme/Dark Mode
public static final int THEME_LIGHT = 0;
public static final int THEME_DARK = 1;
public static final int THEME_AUTO = 2;
}

@ -517,15 +517,15 @@ public class Transaction implements Parcelable
switch (supplementalTxt.charAt(1))
{
case '-':
return R.color.red;
return R.color.negative;
case '+':
return R.color.green;
return R.color.positive;
default:
break;
}
}
return R.color.black;
return R.color.text_primary;
}
public String getDestination(Token token)

@ -732,7 +732,7 @@ public abstract class EthereumNetworkBase implements EthereumNetworkRepositoryTy
}
else
{
return R.color.text_black;
return R.color.text_primary;
}
}

@ -90,4 +90,7 @@ public interface PreferenceRepositoryType {
int getLastVersionCode(int currentCode);
void setLastVersionCode(int code);
int getTheme();
void setTheme(int state);
}

@ -18,6 +18,7 @@ public class SharedPreferenceRepository implements PreferenceRepositoryType {
private static final String NETWORK_FILTER_KEY = "network_filters";
private static final String CUSTOM_NETWORKS_KEY = "custom_networks";
private static final String NOTIFICATIONS_KEY = "notifications";
private static final String THEME_KEY = "theme";
private static final String DEFAULT_SET_KEY = "default_net_set";
private static final String LOCALE_KEY = "locale";
private static final String BACKUP_WALLET_SHOWN = "backup_wallet_shown";
@ -349,4 +350,16 @@ public class SharedPreferenceRepository implements PreferenceRepositoryType {
public void setLastVersionCode(int code) {
pref.edit().putInt(LAST_VERSION_CODE, code).apply();
}
@Override
public int getTheme()
{
return pref.getInt(THEME_KEY, C.THEME_AUTO);
}
@Override
public void setTheme(int state)
{
pref.edit().putInt(THEME_KEY, state).apply();
}
}

@ -1,15 +0,0 @@
package com.alphawallet.app.router;
import android.content.Context;
import android.content.Intent;
import com.alphawallet.app.ui.HelpActivity;
public class HelpRouter {
public void open(Context context) {
Intent intent = new Intent(context, HelpActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(intent);
}
}

@ -61,7 +61,7 @@ public class NotificationService
void DisplayNotification(String title, String content, int priority)
{
checkNotificationPermission();
int color = context.getColor(R.color.holo_blue);
int color = context.getColor(R.color.brand);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent openAppIntent = new Intent(context, HomeActivity.class);
@ -91,7 +91,7 @@ public class NotificationService
void displayPriceAlertNotification(String title, String content, int priority, Intent openAppIntent)
{
checkNotificationPermission();
int color = context.getColor(R.color.holo_blue);
int color = context.getColor(R.color.brand);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

@ -13,21 +13,19 @@ import androidx.lifecycle.ViewModelProvider;
import com.alphawallet.app.R;
import com.alphawallet.app.entity.NetworkInfo;
import com.alphawallet.app.entity.StandardFunctionInterface;
import com.alphawallet.app.repository.EthereumNetworkRepositoryType;
import com.alphawallet.app.viewmodel.CustomNetworkViewModel;
import com.alphawallet.app.widget.FunctionButtonBar;
import com.alphawallet.app.widget.InputView;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.google.android.material.checkbox.MaterialCheckBox;
import java.util.ArrayList;
import java.util.Collections;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;
@AndroidEntryPoint
public class AddCustomRPCNetworkActivity extends BaseActivity implements StandardFunctionInterface {
public class AddCustomRPCNetworkActivity extends BaseActivity implements StandardFunctionInterface
{
public static final String CHAIN_ID = "chain_id";
@ -39,7 +37,7 @@ public class AddCustomRPCNetworkActivity extends BaseActivity implements Standar
private InputView symbolInputView;
private InputView blockExplorerUrlInputView;
private InputView blockExplorerApiUrl;
private SwitchMaterial testNetSwitch;
private MaterialCheckBox testNetCheckBox;
private final Handler handler = new Handler();
@ -50,6 +48,7 @@ public class AddCustomRPCNetworkActivity extends BaseActivity implements Standar
setContentView(R.layout.activity_add_custom_rpc_network);
toolbar();
setTitle(getString(R.string.title_activity_add_custom_rpcnetwork));
nameInputView = findViewById(R.id.input_network_name);
nameInputView.getEditText().setImeOptions(EditorInfo.IME_ACTION_NEXT);
@ -77,41 +76,49 @@ public class AddCustomRPCNetworkActivity extends BaseActivity implements Standar
blockExplorerApiUrl.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
blockExplorerApiUrl.getEditText().setHint("https://api.etherscan.io/api?");
testNetSwitch = findViewById(R.id.testnet_switch);
testNetCheckBox = findViewById(R.id.checkbox_testnet);
initViewModel();
long chainId = getIntent().getLongExtra(CHAIN_ID, -1);
if (chainId >= 0) {
if (chainId >= 0)
{
// get network info and fill ui
NetworkInfo network = viewModel.getNetworkInfo(chainId);
nameInputView.setText(network.name);
rpcUrlInputView.setText(network.rpcServerUrl.replaceAll("(/)([0-9a-fA-F]{32})","/********************************"));
rpcUrlInputView.setText(network.rpcServerUrl.replaceAll("(/)([0-9a-fA-F]{32})", "/********************************"));
chainIdInputView.setText(String.valueOf(network.chainId));
symbolInputView.setText(network.symbol);
blockExplorerUrlInputView.setText(network.etherscanUrl);
blockExplorerApiUrl.setText(network.etherscanAPI);
testNetSwitch.setChecked(viewModel.isTestNetwork(network));
testNetCheckBox.setChecked(viewModel.isTestNetwork(network));
// disable editing for hardcoded networks
if (!network.isCustom) {
if (!network.isCustom)
{
setTitle(getString(R.string.title_network_info));
nameInputView.getEditText().setEnabled(false);
rpcUrlInputView.getEditText().setEnabled(false);
chainIdInputView.getEditText().setEnabled(false);
symbolInputView.getEditText().setEnabled(false);
blockExplorerUrlInputView.getEditText().setEnabled(false);
blockExplorerApiUrl.getEditText().setEnabled(false);
findViewById(R.id.view_click_hider).setVisibility(View.VISIBLE); //disable clicking on the switch
} else {
testNetCheckBox.setEnabled(false);
}
else
{
addFunctionBar(true);
}
} else {
}
else
{
addFunctionBar(false);
}
}
private void addFunctionBar(boolean update) {
private void addFunctionBar(boolean update)
{
FunctionButtonBar functionBar = findViewById(R.id.layoutButtons);
functionBar.setupFunctions(this, new ArrayList<>(Collections.singletonList(update ? R.string.action_update_network : R.string.action_add_network)));
functionBar.revealButtons();
@ -123,27 +130,38 @@ public class AddCustomRPCNetworkActivity extends BaseActivity implements Standar
.get(CustomNetworkViewModel.class);
}
private boolean validateInputs() {
if (TextUtils.isEmpty(nameInputView.getText())) {
private boolean validateInputs()
{
if (TextUtils.isEmpty(nameInputView.getText()))
{
nameInputView.setError(getString(R.string.error_field_required));
return false;
}
if (TextUtils.isEmpty(rpcUrlInputView.getText())) {
if (TextUtils.isEmpty(rpcUrlInputView.getText()))
{
rpcUrlInputView.setError(getString(R.string.error_field_required));
return false;
} else if (!URLUtil.isValidUrl(rpcUrlInputView.getText().toString())) {
}
else if (!URLUtil.isValidUrl(rpcUrlInputView.getText().toString()))
{
rpcUrlInputView.setError(getString(R.string.error_invalid_url));
return false;
}
if (TextUtils.isEmpty(chainIdInputView.getText())) {
if (TextUtils.isEmpty(chainIdInputView.getText()))
{
chainIdInputView.setError(getString(R.string.error_field_required));
return false;
} else {
try {
}
else
{
try
{
Long.parseLong(chainIdInputView.getText().toString());
} catch (NumberFormatException ex) {
}
catch (NumberFormatException ex)
{
chainIdInputView.setError(getString(R.string.error_must_numeric));
return false;
}
@ -151,15 +169,18 @@ public class AddCustomRPCNetworkActivity extends BaseActivity implements Standar
long newChainId = Long.parseLong(chainIdInputView.getText().toString());
long chainId = getIntent().getLongExtra(CHAIN_ID, -1);
if (newChainId != chainId) {
if (newChainId != chainId)
{
NetworkInfo network = viewModel.getNetworkInfo(newChainId);
if (network != null) {
if (network != null)
{
chainIdInputView.setError(getString(R.string.error_chainid_already_taken));
return false;
}
}
if (TextUtils.isEmpty(symbolInputView.getText())) {
if (TextUtils.isEmpty(symbolInputView.getText()))
{
symbolInputView.setError(getString(R.string.error_field_required));
return false;
}
@ -169,7 +190,8 @@ public class AddCustomRPCNetworkActivity extends BaseActivity implements Standar
blockExplorerUrlInputView.setError(getString(R.string.error_field_required));
return false;
} else*/
if (!TextUtils.isEmpty(blockExplorerUrlInputView.getText().toString()) && !URLUtil.isValidUrl(blockExplorerUrlInputView.getText().toString())) {
if (!TextUtils.isEmpty(blockExplorerUrlInputView.getText().toString()) && !URLUtil.isValidUrl(blockExplorerUrlInputView.getText().toString()))
{
blockExplorerUrlInputView.setError(getString(R.string.error_invalid_url));
return false;
}
@ -178,7 +200,8 @@ public class AddCustomRPCNetworkActivity extends BaseActivity implements Standar
blockExplorerApiUrl.setError(getString(R.string.error_field_required));
return false;
} else*/
if (!TextUtils.isEmpty(blockExplorerApiUrl.getText().toString()) && !URLUtil.isValidUrl(blockExplorerApiUrl.getText().toString())) {
if (!TextUtils.isEmpty(blockExplorerApiUrl.getText().toString()) && !URLUtil.isValidUrl(blockExplorerApiUrl.getText().toString()))
{
blockExplorerApiUrl.setError(getString(R.string.error_invalid_url));
return false;
}
@ -186,7 +209,8 @@ public class AddCustomRPCNetworkActivity extends BaseActivity implements Standar
return true;
}
private void resetValidateErrors() {
private void resetValidateErrors()
{
nameInputView.setError(null);
rpcUrlInputView.setError(null);
chainIdInputView.setError(null);
@ -197,7 +221,8 @@ public class AddCustomRPCNetworkActivity extends BaseActivity implements Standar
@Override
public void handleClick(String action, int actionId)
{
if (validateInputs()) {
if (validateInputs())
{
long oldChainId = getIntent().getLongExtra(CHAIN_ID, -1);
// add network
@ -206,9 +231,11 @@ public class AddCustomRPCNetworkActivity extends BaseActivity implements Standar
Long.parseLong(chainIdInputView.getText().toString()),
symbolInputView.getText().toString(),
blockExplorerUrlInputView.getText().toString(),
blockExplorerApiUrl.getText().toString(), testNetSwitch.isChecked(), oldChainId != -1L ? oldChainId : null);
blockExplorerApiUrl.getText().toString(), testNetCheckBox.isChecked(), oldChainId != -1L ? oldChainId : null);
finish();
} else {
}
else
{
handler.postDelayed(this::resetValidateErrors, 2000);
}
}

@ -27,7 +27,7 @@ public class AddEthereumChainPrompt extends BottomSheetDialog implements Standar
private final AddChainListener listener;
public AddEthereumChainPrompt(@NonNull @NotNull Context context, WalletAddEthereumChainObject chainObject, AddChainListener listener) {
super(context, R.style.FullscreenBottomSheetDialogStyle);
super(context);
setContentView(R.layout.dialog_add_ethereum_chain);
this.chainObject = chainObject;
this.listener = listener;

@ -94,10 +94,10 @@ public class AddTokenActivity extends BaseActivity implements AddressReadyCallba
setContentView(R.layout.activity_add_token);
setTitle(getString(R.string.title_add_token));
toolbar();
setTitle(getString(R.string.title_add_token));
counterLayout = findViewById(R.id.layout_progress_counter);
counterText = findViewById(R.id.text_check_counter);

@ -1,11 +1,5 @@
package com.alphawallet.app.ui;
import static com.alphawallet.app.C.CHANGED_LOCALE;
import static com.alphawallet.app.C.CHANGE_CURRENCY;
import static com.alphawallet.app.C.EXTRA_CURRENCY;
import static com.alphawallet.app.C.EXTRA_LOCALE;
import static com.alphawallet.app.C.EXTRA_STATE;
import static com.alphawallet.app.C.PAGE_LOADED;
import static com.alphawallet.app.C.RESET_WALLET;
import android.Manifest;
@ -13,31 +7,23 @@ import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;
import com.alphawallet.app.C;
import com.alphawallet.app.R;
import com.alphawallet.app.repository.EthereumNetworkRepository;
import com.alphawallet.app.util.LocaleUtils;
import com.alphawallet.app.viewmodel.AdvancedSettingsViewModel;
import com.alphawallet.app.widget.AWalletAlertDialog;
import com.alphawallet.app.widget.AWalletConfirmationDialog;
import com.alphawallet.app.widget.SettingsItemView;
import com.bumptech.glide.Glide;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
@ -46,15 +32,14 @@ import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;
@AndroidEntryPoint
public class AdvancedSettingsActivity extends BaseActivity {
public class AdvancedSettingsActivity extends BaseActivity
{
private AdvancedSettingsViewModel viewModel;
private SettingsItemView console;
private SettingsItemView clearBrowserCache;
private SettingsItemView tokenScript;
private SettingsItemView changeLanguage;
private SettingsItemView tokenScriptManagement;
private SettingsItemView changeCurrency;
private SettingsItemView fullScreenSettings;
private SettingsItemView refreshTokenDatabase;
private AWalletAlertDialog waitDialog = null;
@ -63,7 +48,8 @@ public class AdvancedSettingsActivity extends BaseActivity {
private Disposable clearTokenCache;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
viewModel = new ViewModelProvider(this)
.get(AdvancedSettingsViewModel.class);
@ -72,8 +58,6 @@ public class AdvancedSettingsActivity extends BaseActivity {
toolbar();
setTitle(getString(R.string.title_advanced));
viewModel.setLocale(this);
initializeSettings();
addSettingsToLayout();
@ -90,7 +74,8 @@ public class AdvancedSettingsActivity extends BaseActivity {
}
}
private void initializeSettings() {
private void initializeSettings()
{
console = new SettingsItemView.Builder(this)
.withIcon(R.drawable.ic_settings_console)
.withTitle(R.string.title_console)
@ -109,18 +94,6 @@ public class AdvancedSettingsActivity extends BaseActivity {
.withListener(this::onTokenScriptClicked)
.build();
changeLanguage = new SettingsItemView.Builder(this)
.withIcon(R.drawable.ic_settings_language)
.withTitle(R.string.title_change_language)
.withListener(this::onChangeLanguageClicked)
.build();
changeCurrency = new SettingsItemView.Builder(this)
.withIcon(R.drawable.ic_currency)
.withTitle(R.string.settings_locale_currency)
.withListener(this::onChangeCurrencyClicked)
.build();
//TODO Change Icon
tokenScriptManagement = new SettingsItemView.Builder(this)
.withIcon(R.drawable.ic_settings_tokenscript_manage)
@ -129,11 +102,11 @@ public class AdvancedSettingsActivity extends BaseActivity {
.build();
fullScreenSettings = new SettingsItemView.Builder(this)
.withType(SettingsItemView.Type.TOGGLE)
.withIcon(R.drawable.ic_phoneicon)
.withTitle(R.string.fullscreen)
.withListener(this::onFullScreenClicked)
.build();
.withType(SettingsItemView.Type.TOGGLE)
.withIcon(R.drawable.ic_phoneicon)
.withTitle(R.string.fullscreen)
.withListener(this::onFullScreenClicked)
.build();
refreshTokenDatabase = new SettingsItemView.Builder(this)
.withIcon(R.drawable.ic_settings_reset_tokens)
@ -141,7 +114,6 @@ public class AdvancedSettingsActivity extends BaseActivity {
.withListener(this::onReloadTokenDataClicked)
.build();
changeLanguage.setSubtitle(LocaleUtils.getDisplayLanguage(viewModel.getActiveLocale(), viewModel.getActiveLocale()));
fullScreenSettings.setToggleState(viewModel.getFullScreenState());
}
@ -150,7 +122,8 @@ public class AdvancedSettingsActivity extends BaseActivity {
viewModel.setFullScreenState(fullScreenSettings.getToggleState());
}
private void addSettingsToLayout() {
private void addSettingsToLayout()
{
LinearLayout advancedSettingsLayout = findViewById(R.id.layout);
advancedSettingsLayout.addView(console);
advancedSettingsLayout.addView(clearBrowserCache);
@ -158,23 +131,24 @@ public class AdvancedSettingsActivity extends BaseActivity {
if (!checkWritePermission() && EthereumNetworkRepository.extraChains() == null)
advancedSettingsLayout.addView(tokenScript);
advancedSettingsLayout.addView(changeLanguage);
advancedSettingsLayout.addView(changeCurrency);
advancedSettingsLayout.addView(tokenScriptManagement);
advancedSettingsLayout.addView(fullScreenSettings);
advancedSettingsLayout.addView(refreshTokenDatabase);
}
private void onConsoleClicked() {
private void onConsoleClicked()
{
// TODO: Implementation
}
private void onClearBrowserCacheClicked() {
private void onClearBrowserCacheClicked()
{
WebView webView = new WebView(this);
webView.clearCache(true);
viewModel.blankFilterSettings();
Single.fromCallable(() -> {
Single.fromCallable(() ->
{
Glide.get(this).clearDiskCache();
return 1;
}).subscribeOn(Schedulers.io())
@ -186,7 +160,8 @@ public class AdvancedSettingsActivity extends BaseActivity {
}).isDisposed();
}
private void onReloadTokenDataClicked() {
private void onReloadTokenDataClicked()
{
if (clearTokenCache != null && !clearTokenCache.isDisposed())
{
Toast.makeText(this, getString(R.string.token_data_being_cleared), Toast.LENGTH_SHORT).show();
@ -195,7 +170,8 @@ public class AdvancedSettingsActivity extends BaseActivity {
AlertDialog.Builder builder = new AlertDialog.Builder(AdvancedSettingsActivity.this);
AlertDialog dialog = builder.setTitle(R.string.title_reload_token_data)
.setMessage(R.string.reload_token_data_desc)
.setPositiveButton(R.string.action_reload, (d, w) -> {
.setPositiveButton(R.string.action_reload, (d, w) ->
{
//delete all Token data for this wallet
viewModel.stopChainActivity();
showWaitDialog();
@ -220,7 +196,8 @@ public class AdvancedSettingsActivity extends BaseActivity {
waitDialog.setIcon(AWalletAlertDialog.NONE);
waitDialog.setProgressMode();
waitDialog.setCancelable(true);
waitDialog.setOnCancelListener(v -> {
waitDialog.setOnCancelListener(v ->
{
if (clearTokenCache != null && !clearTokenCache.isDisposed()) clearTokenCache.dispose();
});
waitDialog.show();
@ -251,106 +228,51 @@ public class AdvancedSettingsActivity extends BaseActivity {
}
}
private void onTokenScriptClicked() {
private void onTokenScriptClicked()
{
showXMLOverrideDialog();
}
ActivityResultLauncher<Intent> updateLocale = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
updateLocale(result.getData());
});
ActivityResultLauncher<Intent> updateCurrency = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
updateCurrency(result.getData());
});
private void onChangeLanguageClicked() {
Intent intent = new Intent(this, SelectLocaleActivity.class);
String selectedLocale = viewModel.getActiveLocale();
intent.putExtra(EXTRA_LOCALE, selectedLocale);
intent.putParcelableArrayListExtra(EXTRA_STATE, viewModel.getLocaleList(this));
updateLocale.launch(intent);
}
private void onChangeCurrencyClicked() {
Intent intent = new Intent(this, SelectCurrencyActivity.class);
String currentLocale = viewModel.getDefaultCurrency();
intent.putExtra(EXTRA_CURRENCY, currentLocale);
intent.putParcelableArrayListExtra(EXTRA_STATE, viewModel.getCurrencyList());
updateCurrency.launch(intent);
}
private void onTokenScriptManagementClicked() {
private void onTokenScriptManagementClicked()
{
Intent intent = new Intent(this, TokenScriptManagementActivity.class);
startActivity(intent);
}
private void showXMLOverrideDialog() {
private void showXMLOverrideDialog()
{
AWalletConfirmationDialog cDialog = new AWalletConfirmationDialog(this);
cDialog.setTitle(R.string.enable_xml_override_dir);
cDialog.setSmallText(R.string.explain_xml_override);
cDialog.setMediumText(R.string.ask_user_about_xml_override);
cDialog.setPrimaryButtonText(R.string.dialog_ok);
cDialog.setPrimaryButtonListener(v -> {
cDialog.setPrimaryButtonListener(v ->
{
//ask for OS permission and write directory
askWritePermission();
cDialog.dismiss();
});
cDialog.setSecondaryButtonText(R.string.dialog_cancel_back);
cDialog.setSecondaryButtonListener(v -> {
cDialog.setSecondaryButtonListener(v ->
{
cDialog.dismiss();
});
cDialog.show();
}
private void askWritePermission() {
private void askWritePermission()
{
final String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
Timber.w("Folder write permission is not granted. Requesting permission");
ActivityCompat.requestPermissions(this, permissions, HomeActivity.RC_ASSET_EXTERNAL_WRITE_PERM);
}
private boolean checkWritePermission() {
private boolean checkWritePermission()
{
return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED;
}
public void updateLocale(Intent data) {
if (data != null)
{
String newLocale = data.getStringExtra(C.EXTRA_LOCALE);
String oldLocale = viewModel.getActiveLocale();
if (!TextUtils.isEmpty(newLocale) && !newLocale.equals(oldLocale))
{
viewModel.updateLocale(newLocale, this);
Intent intent = new Intent();
setResult(RESULT_OK, intent);
intent.putExtra(CHANGED_LOCALE, true);
finish();
}
}
}
public void updateCurrency(Intent data)
{
if (data == null) return;
String currencyCode = data.getStringExtra(C.EXTRA_CURRENCY);
//Check if selected currency code is previous selected one then don't update
if(viewModel.getDefaultCurrency().equals(currencyCode)) return;
viewModel.updateCurrency(currencyCode)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(res -> {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
intent.putExtra(CHANGE_CURRENCY, true);
finish();
})
.isDisposed();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
@ -370,22 +292,23 @@ public class AdvancedSettingsActivity extends BaseActivity {
}
}
private void showAlphaWalletDirectoryConfirmation() {
private void showAlphaWalletDirectoryConfirmation()
{
AWalletAlertDialog cDialog = new AWalletAlertDialog(this);
cDialog.setIcon(AWalletAlertDialog.SUCCESS);
cDialog.setTitle(getString(R.string.created_aw_directory));
cDialog.setMessage(getString(R.string.created_aw_directory_detail));
cDialog.setButtonText(R.string.dialog_ok);
cDialog.setButtonListener(v -> {
cDialog.setButtonListener(v ->
{
cDialog.dismiss();
});
cDialog.show();
}
@Override
protected void onResume() {
protected void onResume()
{
super.onResume();
changeCurrency.setSubtitle(viewModel.getDefaultCurrency());
}
}

@ -1,5 +1,7 @@
package com.alphawallet.app.ui;
import static com.alphawallet.app.C.Key.WALLET;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
@ -9,8 +11,6 @@ import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
@ -22,7 +22,6 @@ import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.core.content.res.ResourcesCompat;
import androidx.lifecycle.ViewModelProvider;
import com.alphawallet.app.R;
@ -36,7 +35,6 @@ import com.alphawallet.app.entity.Wallet;
import com.alphawallet.app.entity.WalletType;
import com.alphawallet.app.service.KeyService;
import com.alphawallet.app.ui.QRScanning.DisplayUtils;
import com.alphawallet.app.util.Utils;
import com.alphawallet.app.viewmodel.BackupKeyViewModel;
import com.alphawallet.app.widget.AWalletAlertDialog;
import com.alphawallet.app.widget.FunctionButtonBar;
@ -45,17 +43,14 @@ import com.alphawallet.app.widget.PasswordInputView;
import com.alphawallet.app.widget.SignTransactionDialog;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayout;
import com.google.android.material.card.MaterialCardView;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;
import static com.alphawallet.app.C.Key.WALLET;
@AndroidEntryPoint
public class BackupKeyActivity extends BaseActivity implements
View.OnClickListener,
@ -64,7 +59,8 @@ public class BackupKeyActivity extends BaseActivity implements
SignAuthenticationCallback,
Runnable,
LayoutCallbackListener,
StandardFunctionInterface {
StandardFunctionInterface
{
BackupKeyViewModel viewModel;
@ -76,6 +72,7 @@ public class BackupKeyActivity extends BaseActivity implements
private PasswordInputView inputView;
private ImageView backupImage;
private TextView verifyTextBox;
private MaterialCardView verifyTextContainer;
private String[] mnemonicArray;
private LinearLayout successOverlay;
private final Handler handler = new Handler();
@ -88,7 +85,8 @@ public class BackupKeyActivity extends BaseActivity implements
private int screenWidth;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
secureWindow();
@ -99,6 +97,7 @@ public class BackupKeyActivity extends BaseActivity implements
initViewModel();
screenWidth = DisplayUtils.getScreenResolution(this).x;
wallet = getIntent().getParcelableExtra(WALLET);
if (Objects.requireNonNull(getIntent().getExtras()).containsKey("STATE"))
@ -111,11 +110,13 @@ public class BackupKeyActivity extends BaseActivity implements
}
}
private void initBackupState() {
private void initBackupState()
{
state = (BackupState) getIntent().getSerializableExtra("STATE");
assert state != null;
switch (state) {
switch (state)
{
case SHOW_SEED_PHRASE_SINGLE:
showSeedPhrase();
break;
@ -144,19 +145,22 @@ public class BackupKeyActivity extends BaseActivity implements
}
}
private void showSeedPhrase() {
private void showSeedPhrase()
{
setupTestSeed();
((TextView)findViewById(R.id.text_title)).setText(R.string.your_seed_phrase);
((TextView) findViewById(R.id.text_title)).setText(R.string.your_seed_phrase);
DisplaySeed();
functionButtonBar.setPrimaryButtonText(R.string.hide_seed_text);
functionButtonBar.setPrimaryButtonClickListener(this);
}
private void initBackupType() {
private void initBackupType()
{
BackupOperationType type = (BackupOperationType) getIntent().getSerializableExtra("TYPE");
if (type == null) type = BackupOperationType.UNDEFINED;
switch (type) {
switch (type)
{
case UNDEFINED:
state = BackupState.UNDEFINED;
DisplayKeyFailureDialog("Unknown Key operation");
@ -186,28 +190,37 @@ public class BackupKeyActivity extends BaseActivity implements
}
@SuppressLint("SourceLockedOrientationActivity")
private void lockOrientation() {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
private void lockOrientation()
{
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
}
else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
private void setupUpgradeKey(boolean showSuccess) {
private void setupUpgradeKey(boolean showSuccess)
{
setContentView(R.layout.activity_backup);
initViews();
successOverlay = findViewById(R.id.layout_success_overlay);
if (successOverlay != null && showSuccess) {
if (successOverlay != null && showSuccess)
{
successOverlay.setVisibility(View.VISIBLE);
handler.postDelayed(this, 1000);
}
state = BackupState.UPGRADE_KEY_SECURITY;
if (wallet.type == WalletType.KEYSTORE) {
if (wallet.type == WalletType.KEYSTORE)
{
title.setText(R.string.lock_keystore_upgrade);
} else {
}
else
{
title.setText(R.string.lock_key_upgrade);
}
backupImage.setImageResource(R.drawable.biometrics);
@ -215,9 +228,12 @@ public class BackupKeyActivity extends BaseActivity implements
detail.setText(R.string.upgrade_key_security_detail);
int res;
if (wallet.type == WalletType.HDKEY) {
if (wallet.type == WalletType.HDKEY)
{
res = R.string.lock_seed_phrase;
} else {
}
else
{
res = R.string.action_upgrade_key;
}
@ -228,7 +244,8 @@ public class BackupKeyActivity extends BaseActivity implements
@Override
public void keyUpgraded(final KeyService.UpgradeKeyResult result)
{
handler.post(() -> {
handler.post(() ->
{
switch (result)
{
case REQUESTING_SECURITY: //Deprecated
@ -252,8 +269,10 @@ public class BackupKeyActivity extends BaseActivity implements
});
}
private void upgradeKeySecurity() {
switch (wallet.type) {
private void upgradeKeySecurity()
{
switch (wallet.type)
{
case KEYSTORE:
case KEYSTORE_LEGACY:
case HDKEY:
@ -266,11 +285,14 @@ public class BackupKeyActivity extends BaseActivity implements
}
@Override
public void createdKey(String address) {
public void createdKey(String address)
{
//key upgraded
//store wallet upgrade
if (wallet.address.equalsIgnoreCase(address)) {
switch (wallet.type) {
if (wallet.address.equalsIgnoreCase(address))
{
switch (wallet.type)
{
case KEYSTORE_LEGACY:
case KEYSTORE:
case HDKEY:
@ -284,7 +306,8 @@ public class BackupKeyActivity extends BaseActivity implements
}
}
private void setupTestSeed() {
private void setupTestSeed()
{
setContentView(R.layout.activity_backup_write_seed);
initViews();
}
@ -306,14 +329,16 @@ public class BackupKeyActivity extends BaseActivity implements
}
@Override
public void onPause() {
public void onPause()
{
super.onPause();
viewModel.resetSignDialog();
//hide seed phrase and any visible words
if (layoutWordHolder != null) layoutWordHolder.removeAllViews();
switch (state) {
switch (state)
{
case WRITE_DOWN_SEED_PHRASE:
case SHOW_SEED_PHRASE:
//note, the OS calls onPause if user chooses to authenticate using PIN or password (takes them to the auth screen).
@ -343,15 +368,18 @@ public class BackupKeyActivity extends BaseActivity implements
}
}
private void initViews() {
private void initViews()
{
title = findViewById(R.id.text_title);
detail = findViewById(R.id.text_detail);
layoutWordHolder = findViewById(R.id.layout_word_holder);
verifyTextBox = findViewById(R.id.text_verify);
verifyTextContainer = findViewById(R.id.container);
backupImage = findViewById(R.id.backup_seed_image);
functionButtonBar = findViewById(R.id.layoutButtons);
inputView = findViewById(R.id.input_password);
if (inputView != null) {
if (inputView != null)
{
inputView.getEditText().addTextChangedListener(this);
}
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
@ -360,9 +388,12 @@ public class BackupKeyActivity extends BaseActivity implements
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
{
onBackPressed();
return true;
}
@ -371,8 +402,10 @@ public class BackupKeyActivity extends BaseActivity implements
}
@Override
public void onBackPressed() {
switch (state) {
public void onBackPressed()
{
switch (state)
{
case VERIFY_SEED_PHRASE:
case SEED_PHRASE_INVALID:
//if we're currently verifying seed or we made a mistake copying the seed down then allow user to restart
@ -400,20 +433,24 @@ public class BackupKeyActivity extends BaseActivity implements
}
@Override
public void onClick(View view) {
public void onClick(View view)
{
// Passing an empty String as this class handles clicks based on state
handleClick("", 0);
}
private void ResetInputBox() {
verifyTextBox.setBackgroundResource(R.drawable.background_verify_window);
verifyTextBox.setTextColor(getColor(R.color.dove));
private void ResetInputBox()
{
// Removed - currently not needed
// verifyTextContainer.setStrokeColor(ContextCompat.getColor(this, R.color.text_secondary));
// verifyTextBox.setTextColor(getColor(R.color.text_secondary));
verifyTextBox.setText(R.string.empty);
TextView invalid = findViewById(R.id.text_invalid);
invalid.setVisibility(View.GONE);
}
private void JSONBackup() {
private void JSONBackup()
{
setContentView(R.layout.activity_set_json_password);
initViews();
setTitle(getString(R.string.set_keystore_password));
@ -426,17 +463,23 @@ public class BackupKeyActivity extends BaseActivity implements
inputView.setLayoutListener(this, this);
}
private void TestSeedPhrase() {
private void TestSeedPhrase()
{
String currentText = verifyTextBox.getText().toString();
String[] currentTest = currentText.split(" ");
if (currentTest.length != mnemonicArray.length) {
if (currentTest.length != mnemonicArray.length)
{
//fail. This should never happen
seedIncorrect();
return;
} else {
for (int i = 0; i < mnemonicArray.length; i++) {
if (!mnemonicArray[i].equals(currentTest[i])) {
}
else
{
for (int i = 0; i < mnemonicArray.length; i++)
{
if (!mnemonicArray[i].equals(currentTest[i]))
{
seedIncorrect();
return;
}
@ -450,22 +493,27 @@ public class BackupKeyActivity extends BaseActivity implements
backupKeySuccess(BackupOperationType.BACKUP_HD_KEY);
}
private void seedIncorrect() {
verifyTextBox.setBackgroundResource(R.drawable.background_verify_window_fail);
verifyTextBox.setTextColor(getColor(R.color.dove));
TextView invalid = findViewById(R.id.text_invalid);
invalid.setVisibility(View.VISIBLE);
private void seedIncorrect()
{
// Removed for now:
// The color switch is not shown anyway because ResetInputBox() is called immediately after
// verifyTextContainer.setStrokeColor(ContextCompat.getColor(this, R.color.negative));
// verifyTextBox.setTextColor(getColor(R.color.text_secondary));
// TextView invalid = findViewById(R.id.text_invalid);
// invalid.setVisibility(View.VISIBLE);
Toast.makeText(this, R.string.invalid_phrase, Toast.LENGTH_LONG).show();
ResetInputBox();
VerifySeedPhrase();
}
private void backupKeySuccess(BackupOperationType type) {
private void backupKeySuccess(BackupOperationType type)
{
//first record backup time success, in case user aborts operation during key locking
viewModel.backupSuccess(wallet);
//now ask if user wants to upgrade the key security (if required)
switch (wallet.authLevel) {
switch (wallet.authLevel)
{
case STRONGBOX_NO_AUTHENTICATION:
case TEE_NO_AUTHENTICATION:
//improve key security
@ -477,11 +525,13 @@ public class BackupKeyActivity extends BaseActivity implements
}
}
private void finishBackupSuccess(boolean upgradeKey) {
private void finishBackupSuccess(boolean upgradeKey)
{
state = BackupState.SEED_PHRASE_VALIDATED;
Intent intent = new Intent();
switch (wallet.type) {
switch (wallet.type)
{
case KEYSTORE_LEGACY:
case KEYSTORE:
intent.putExtra("TYPE", BackupOperationType.BACKUP_KEYSTORE_KEY);
@ -500,7 +550,8 @@ public class BackupKeyActivity extends BaseActivity implements
finish();
}
private void VerifySeedPhrase() {
private void VerifySeedPhrase()
{
setContentView(R.layout.activity_verify_seed_phrase);
initViews();
functionButtonBar.setPrimaryButtonText(R.string.action_continue);
@ -513,17 +564,20 @@ public class BackupKeyActivity extends BaseActivity implements
layoutWordHolder.setVisibility(View.VISIBLE);
layoutWordHolder.removeAllViews();
if (mnemonicArray != null) {
if (mnemonicArray != null)
{
jumbleList();
}
}
private void jumbleList() {
private void jumbleList()
{
List<Integer> numberList = new ArrayList<>();
for (int i = 0; i < mnemonicArray.length; i++)
numberList.add(i);
for (int i = 0; i < mnemonicArray.length; i++) {
for (int i = 0; i < mnemonicArray.length; i++)
{
int random = (int) (Math.random() * (double) numberList.size());
int mnemonicIndex = numberList.get(random);
numberList.remove(random); //remove this index
@ -533,9 +587,9 @@ public class BackupKeyActivity extends BaseActivity implements
}
}
private void onWordClick(TextView tv) {
tv.setTextColor(getColor(R.color.alabaster));
tv.setBackgroundResource(R.drawable.background_seed_word_selected);
private void onWordClick(TextView tv)
{
tv.setSelected(true);
tv.setOnClickListener(null);
String currentText = verifyTextBox.getText().toString();
if (currentText.length() > 0) currentText += " ";
@ -549,7 +603,8 @@ public class BackupKeyActivity extends BaseActivity implements
}
}
private void WriteDownSeedPhrase() {
private void WriteDownSeedPhrase()
{
setContentView(R.layout.activity_backup_write_seed);
initViews();
state = BackupState.WRITE_DOWN_SEED_PHRASE;
@ -558,7 +613,8 @@ public class BackupKeyActivity extends BaseActivity implements
functionButtonBar.setPrimaryButtonClickListener(this);
}
private void DisplaySeed() {
private void DisplaySeed()
{
if (layoutWordHolder != null)
{
layoutWordHolder.setVisibility(View.VISIBLE);
@ -568,50 +624,29 @@ public class BackupKeyActivity extends BaseActivity implements
viewModel.getAuthentication(wallet, this, this);
}
private TextView generateSeedWordTextView(String word) {
int margin = Utils.dp2px(this, 4);
int padding;
float textSize;
int textViewHeight;
if (screenWidth > 800)
{
textSize = 16.0f;
padding = Utils.dp2px(this, 20);
textViewHeight = Utils.dp2px(this, 44);
}
else
{
textSize = 14.0f;
padding = Utils.dp2px(this, 16);
textViewHeight = Utils.dp2px(this, 38);
}
private TextView generateSeedWordTextView(String word)
{
int margin = (int) getResources().getDimension(R.dimen.mini_4);
FlexboxLayout.LayoutParams params =
new FlexboxLayout.LayoutParams(FlexboxLayout.LayoutParams.WRAP_CONTENT, textViewHeight);
new FlexboxLayout.LayoutParams(FlexboxLayout.LayoutParams.WRAP_CONTENT, FlexboxLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(margin, margin, margin, margin);
TextView seedWord = new TextView(this);
seedWord.setMaxLines(1);
TextView seedWord = new TextView(this, null, R.attr.seedWordStyle);
seedWord.setText(word);
seedWord.setTypeface(ResourcesCompat.getFont(this, R.font.font_regular));
seedWord.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
seedWord.setBackgroundResource(R.drawable.background_seed_word);
seedWord.setTextColor(getColor(R.color.mine));
seedWord.setLayoutParams(params);
seedWord.setGravity(Gravity.CENTER);
seedWord.setPadding(padding, 0, padding, 0);
return seedWord;
}
@Override
public void HDKeyCreated(String address, Context ctx, KeyService.AuthenticationLevel level) {
public void HDKeyCreated(String address, Context ctx, KeyService.AuthenticationLevel level)
{
//empty, doesn't get called
}
@Override
public void keyFailure(String message) {
public void keyFailure(String message)
{
if (message != null && message.length() > 0)
{
DisplayKeyFailureDialog(message);
@ -625,7 +660,8 @@ public class BackupKeyActivity extends BaseActivity implements
}
}
private void DisplayKeyFailureDialog(String message) {
private void DisplayKeyFailureDialog(String message)
{
hideDialog();
alertDialog = new AWalletAlertDialog(this);
@ -634,20 +670,25 @@ public class BackupKeyActivity extends BaseActivity implements
alertDialog.setMessage(message);
alertDialog.setButtonText(R.string.action_continue);
alertDialog.setCanceledOnTouchOutside(true);
alertDialog.setButtonListener(v -> {
alertDialog.setButtonListener(v ->
{
cancelAuthentication();
alertDialog.dismiss();
});
alertDialog.setOnCancelListener(v -> {
alertDialog.setOnCancelListener(v ->
{
cancelAuthentication();
});
alertDialog.show();
}
@Override
public void fetchMnemonic(String mnemonic) {
handler.post(() -> {
switch (state) {
public void fetchMnemonic(String mnemonic)
{
handler.post(() ->
{
switch (state)
{
case WRITE_DOWN_SEED_PHRASE:
WriteDownSeedPhrase();
mnemonicArray = mnemonic.split(" ");
@ -678,11 +719,13 @@ public class BackupKeyActivity extends BaseActivity implements
});
}
private void addSeedWordsToScreen() {
private void addSeedWordsToScreen()
{
if (mnemonicArray == null) return;
layoutWordHolder.setFlexDirection(FlexDirection.ROW);
for (String word : mnemonicArray) {
for (String word : mnemonicArray)
{
layoutWordHolder.addView(generateSeedWordTextView(word));
}
}
@ -736,22 +779,28 @@ public class BackupKeyActivity extends BaseActivity implements
finish();
}
private void initViewModel() {
private void initViewModel()
{
viewModel = new ViewModelProvider(this)
.get(BackupKeyViewModel.class);
viewModel.exportedStore().observe(this, this::onExportKeystore);
}
ActivityResultLauncher<Intent> handleBackupWallet = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
result ->
{
if (result.getResultCode() == RESULT_OK)
{
backupKeySuccess(BackupOperationType.BACKUP_KEYSTORE_KEY);
} else {
}
else
{
AskUserSuccess();
}
});
private void onExportKeystore(String keystore) {
private void onExportKeystore(String keystore)
{
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Keystore");
@ -760,7 +809,8 @@ public class BackupKeyActivity extends BaseActivity implements
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Operation taskCode = null;
@ -768,60 +818,74 @@ public class BackupKeyActivity extends BaseActivity implements
//Interpret the return code; if it's within the range of values possible to return from PIN confirmation then separate out
//the task code from the return value. We have to do it this way because there's no way to send a bundle across the PIN dialog
//and out through the PIN dialog's return back to here
if (requestCode >= SignTransactionDialog.REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS && requestCode <= SignTransactionDialog.REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS + 10) {
if (requestCode >= SignTransactionDialog.REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS && requestCode <= SignTransactionDialog.REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS + 10)
{
taskCode = Operation.values()[requestCode - SignTransactionDialog.REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS];
requestCode = SignTransactionDialog.REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS;
}
switch (requestCode) {
switch (requestCode)
{
case SignTransactionDialog.REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS:
if (resultCode == RESULT_OK) {
if (resultCode == RESULT_OK)
{
viewModel.completeAuthentication(taskCode);
} else {
}
else
{
viewModel.failedAuthentication(taskCode);
}
break;
}
}
private void AskUserSuccess() {
private void AskUserSuccess()
{
hideDialog();
alertDialog = new AWalletAlertDialog(this);
alertDialog.setIcon(AWalletAlertDialog.SUCCESS);
alertDialog.setTitle(R.string.do_manage_make_backup);
alertDialog.setButtonText(R.string.yes_continue);
alertDialog.setButtonListener(v -> {
alertDialog.setButtonListener(v ->
{
hideDialog();
backupKeySuccess(BackupOperationType.BACKUP_KEYSTORE_KEY);
});
alertDialog.setSecondaryButtonText(R.string.no_repeat);
alertDialog.setSecondaryButtonListener(v -> {
alertDialog.setSecondaryButtonListener(v ->
{
hideDialog();
cancelAuthentication();
});
alertDialog.show();
}
private void hideDialog() {
if (alertDialog != null && alertDialog.isShowing()) {
private void hideDialog()
{
if (alertDialog != null && alertDialog.isShowing())
{
alertDialog.dismiss();
alertDialog = null;
}
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
@Override
public void afterTextChanged(Editable editable) {
switch (state) {
public void afterTextChanged(Editable editable)
{
switch (state)
{
case ENTER_BACKUP_STATE_HD:
break;
case WRITE_DOWN_SEED_PHRASE:
@ -843,17 +907,20 @@ public class BackupKeyActivity extends BaseActivity implements
}
@Override
public void onLayoutShrunk() {
public void onLayoutShrunk()
{
}
@Override
public void onLayoutExpand() {
public void onLayoutExpand()
{
}
@Override
public void onInputDoneClick(View view) {
public void onInputDoneClick(View view)
{
inputView = findViewById(R.id.input_password);
keystorePassword = inputView.getText().toString();
if (keystorePassword.length() > 5)
@ -868,8 +935,10 @@ public class BackupKeyActivity extends BaseActivity implements
}
@Override
public void handleClick(String action, int id) {
switch (state) {
public void handleClick(String action, int id)
{
switch (state)
{
case ENTER_BACKUP_STATE_HD:
WriteDownSeedPhrase();
DisplaySeed();

@ -18,7 +18,7 @@ public abstract class BaseActivity extends AppCompatActivity {
Toolbar toolbar = findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
toolbar.setTitle(R.string.empty);
}
enableDisplayHomeAsUp();
return toolbar;

@ -464,8 +464,7 @@ public class DappBrowserFragment extends BaseFragment implements OnSignTransacti
layoutNavigation = view.findViewById(R.id.layout_navigator);
View home = view.findViewById(R.id.home);
home.setOnClickListener(v -> homePressed());
if (home != null) home.setOnClickListener(v -> homePressed());
//If you are wondering about the strange way the menus are inflated - this is required to ensure
//that the menu text gets created with the correct localisation under every circumstance
@ -480,7 +479,6 @@ public class DappBrowserFragment extends BaseFragment implements OnSignTransacti
}
refresh = view.findViewById(R.id.refresh);
RelativeLayout layout = view.findViewById(R.id.address_bar_layout);
layout.getLayoutTransition().enableTransitionType(LayoutTransition.CHANGING);

@ -329,7 +329,7 @@ public class Erc20DetailActivity extends BaseActivity implements StandardFunctio
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// getMenuInflater().inflate(R.menu.menu_qr, menu);
// getMenuInflater().inflate(R.menu.menu_show_contract, menu);
return super.onCreateOptionsMenu(menu);
}
@ -340,7 +340,7 @@ public class Erc20DetailActivity extends BaseActivity implements StandardFunctio
{
finish();
}
else if (item.getItemId() == R.id.action_qr)
else if (item.getItemId() == R.id.action_show_contract)
{
viewModel.showContractInfo(this, wallet, token);
}

@ -41,7 +41,6 @@ import com.alphawallet.app.widget.AWalletAlertDialog;
import com.alphawallet.app.widget.ActionSheetDialog;
import com.alphawallet.app.widget.FunctionButtonBar;
import com.alphawallet.app.widget.SignTransactionDialog;
import com.alphawallet.app.widget.SystemView;
import com.alphawallet.ethereum.EthereumNetworkBase;
import com.alphawallet.token.entity.Attribute;
import com.alphawallet.token.entity.EthereumMessage;
@ -93,7 +92,6 @@ public class FunctionActivity extends BaseActivity implements FunctionCallback,
private List<BigInteger> tokenIds;
private BigInteger tokenId;
private String actionMethod;
private SystemView systemView;
private Web3TokenView tokenView;
private final Map<String, String> args = new HashMap<>();
private StringBuilder attrs;
@ -275,8 +273,6 @@ public class FunctionActivity extends BaseActivity implements FunctionCallback,
{
viewModel = new ViewModelProvider(this)
.get(TokenFunctionViewModel.class);
systemView = findViewById(R.id.system_view);
systemView.hide();
viewModel.invalidAddress().observe(this, this::errorInvalidAddress);
viewModel.insufficientFunds().observe(this, this::errorInsufficientFunds);
}

@ -8,21 +8,21 @@ import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
@ -44,6 +44,7 @@ import com.alphawallet.app.util.BalanceUtils;
import com.alphawallet.app.util.Utils;
import com.alphawallet.app.viewmodel.GasSettingsViewModel;
import com.alphawallet.app.widget.GasSliderView;
import com.google.android.material.radiobutton.MaterialRadioButton;
import java.math.BigDecimal;
import java.math.BigInteger;
@ -52,8 +53,6 @@ import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;
import io.realm.Realm;
import io.realm.RealmQuery;
@ -96,12 +95,13 @@ public class GasSettingsActivity extends BaseActivity implements GasSettingsCall
private Warning warningType = Warning.OFF;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gas_settings);
toolbar();
setTitle(R.string.set_speed_title);
setTitle(getString(R.string.set_speed_title));
gasSliderView = findViewById(R.id.gasSliderView);
recyclerView = findViewById(R.id.list);
@ -152,7 +152,8 @@ public class GasSettingsActivity extends BaseActivity implements GasSettingsCall
{
if (realmGasSpread != null) realmGasSpread.removeAllChangeListeners();
realmGasSpread = getGasQuery().findFirstAsync();
realmGasSpread.addChangeListener(realmToken -> {
realmGasSpread.addChangeListener(realmToken ->
{
if (realmGasSpread.isValid())
{
GasPriceSpread gs = ((RealmGasSpread) realmToken).getGasPrice();
@ -224,7 +225,8 @@ public class GasSettingsActivity extends BaseActivity implements GasSettingsCall
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
public boolean onCreateOptionsMenu(Menu menu)
{
return super.onCreateOptionsMenu(menu);
}
@ -247,21 +249,23 @@ public class GasSettingsActivity extends BaseActivity implements GasSettingsCall
adapter.notifyItemChanged(customIndex);
}
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder>
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.GasSpeedHolder>
{
private final Token baseCurrency;
private final Context context;
@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
public GasSpeedHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_gas_speed, parent, false);
return new CustomViewHolder(itemView);
return new GasSpeedHolder(itemView);
}
class CustomViewHolder extends RecyclerView.ViewHolder {
final ImageView checkbox;
class GasSpeedHolder extends RecyclerView.ViewHolder
{
final MaterialRadioButton radio;
final TextView speedName;
final TextView speedGwei;
final TextView speedCostEth;
@ -272,10 +276,10 @@ public class GasSettingsActivity extends BaseActivity implements GasSettingsCall
final LinearLayout warning;
final TextView warningText;
CustomViewHolder(View view)
GasSpeedHolder(View view)
{
super(view);
checkbox = view.findViewById(R.id.checkbox);
radio = view.findViewById(R.id.radio);
speedName = view.findViewById(R.id.text_speed);
speedCostFiat = view.findViewById(R.id.text_speed_cost);
speedCostEth = view.findViewById(R.id.text_speed_cost_eth);
@ -295,7 +299,7 @@ public class GasSettingsActivity extends BaseActivity implements GasSettingsCall
}
@Override
public void onBindViewHolder(CustomAdapter.CustomViewHolder holder, int p)
public void onBindViewHolder(GasSpeedHolder holder, int p)
{
BigDecimal useGasLimit = presetGasLimit;
int position = holder.getAbsoluteAdapterPosition();
@ -305,8 +309,22 @@ public class GasSettingsActivity extends BaseActivity implements GasSettingsCall
holder.speedName.setVisibility(View.VISIBLE);
holder.warning.setVisibility(View.GONE);
holder.checkbox.setSelected(position == currentGasSpeedIndex);
holder.itemLayout.setOnClickListener(v -> {
holder.radio.setOnCheckedChangeListener((compoundButton, checked) ->
{
if (checked)
{
holder.speedName.setTypeface(ResourcesCompat.getFont(getApplicationContext(), R.font.font_bold));
}
else
{
holder.speedName.setTypeface(ResourcesCompat.getFont(getApplicationContext(), R.font.font_regular));
}
});
holder.radio.setChecked(position == currentGasSpeedIndex);
holder.itemLayout.setOnClickListener(v ->
{
if (position == customIndex && currentGasSpeedIndex != customIndex)
{
gasSliderView.initGasLimit(customGasLimit.toBigInteger());
@ -363,7 +381,8 @@ public class GasSettingsActivity extends BaseActivity implements GasSettingsCall
BigDecimal gasFee = new BigDecimal(gs.gasPrice).multiply(useGasLimit);
String gasAmountInBase = BalanceUtils.getScaledValueScientific(gasFee, baseCurrency.tokenInfo.decimals, GAS_PRECISION);
if (gasAmountInBase.equals("0")) gasAmountInBase = "0.00001"; //NB no need to allow for zero gas chains; this activity wouldn't appear
if (gasAmountInBase.equals("0"))
gasAmountInBase = "0.00001"; //NB no need to allow for zero gas chains; this activity wouldn't appear
String displayStr = context.getString(R.string.gas_amount, gasAmountInBase, baseCurrency.getSymbol());
String displayTime = context.getString(R.string.gas_time_suffix,
Utils.shortConvertTimePeriodInSeconds(gs.seconds, context));
@ -387,9 +406,9 @@ public class GasSettingsActivity extends BaseActivity implements GasSettingsCall
//This collapses the view if it's not required, eg for re-send transaction
//This hides the views that aren't selectable due to gas too low
if(minGasPrice > 0)
if (minGasPrice > 0)
{
if(!gs.isCustom && gs.gasPrice.longValue() < minGasPrice)
if (!gs.isCustom && gs.gasPrice.longValue() < minGasPrice)
{
ViewGroup.LayoutParams params = holder.itemLayout.getLayoutParams();
params.height = 0;
@ -403,7 +422,7 @@ public class GasSettingsActivity extends BaseActivity implements GasSettingsCall
checkInsufficientGas(txCost);
}
private void blankCustomHolder(CustomViewHolder holder)
private void blankCustomHolder(GasSpeedHolder holder)
{
holder.speedGwei.setText(context.getString(R.string.bracketed, context.getString(R.string.set_your_speed)));
holder.speedCostEth.setText("");
@ -503,19 +522,23 @@ public class GasSettingsActivity extends BaseActivity implements GasSettingsCall
expectedTime = (long) ((double) lg.seconds - extrapolateFactor * timeDiff);
break;
}
else if (lg.speed.equals(getString(R.string.speed_slow))) { //final entry
else if (lg.speed.equals(getString(R.string.speed_slow)))
{ //final entry
//danger zone - transaction may not complete
double dangerAmount = lowerBound / 2.0;
long dangerTime = 12 * DateUtils.HOUR_IN_MILLIS / 1000;
if (dGasPrice < (lowerBound*0.95)) //only show gas warning if less than 95% of slow
if (dGasPrice < (lowerBound * 0.95)) //only show gas warning if less than 95% of slow
{
showGasWarning(false);
}
if (dGasPrice < dangerAmount) {
if (dGasPrice < dangerAmount)
{
expectedTime = -1; //never
} else {
}
else
{
expectedTime = extrapolateTime(dangerTime, lg.seconds, dGasPrice, dangerAmount, lowerBound);
}
@ -595,7 +618,7 @@ public class GasSettingsActivity extends BaseActivity implements GasSettingsCall
gasWarning.setVisibility(View.VISIBLE);
EditText gas_price_entry = findViewById(R.id.gas_price_entry);
gas_price_entry.setTextColor(getColor(R.color.danger));
gas_price_entry.setTextColor(getColor(R.color.error));
gas_price_entry.setBackground(ContextCompat.getDrawable(this, R.drawable.background_text_edit_error));
}
}
@ -614,7 +637,7 @@ public class GasSettingsActivity extends BaseActivity implements GasSettingsCall
warningType = Warning.OFF;
EditText gas_price_entry = findViewById(R.id.gas_price_entry);
gas_price_entry.setTextColor(getColor(R.color.dove));
gas_price_entry.setTextColor(getColor(R.color.text_secondary));
gas_price_entry.setBackground(AppCompatResources.getDrawable(this, R.drawable.background_password_entry));
}

@ -1,188 +0,0 @@
package com.alphawallet.app.ui;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.RawRes;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.LinearLayout;
import com.alphawallet.app.entity.MediaLinks;
import com.alphawallet.app.ui.widget.adapter.HelpAdapter;
import com.alphawallet.app.R;
import com.alphawallet.app.entity.HelpItem;
import com.alphawallet.app.viewmodel.HelpViewModel;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;
import timber.log.Timber;
@AndroidEntryPoint
public class HelpActivity extends BaseActivity {
private HelpViewModel viewModel;
private WebView webView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_help);
toolbar();
setTitle(getString(R.string.toolbar_header_help));
RecyclerView list = findViewById(R.id.list_help);
list.setLayoutManager(new LinearLayoutManager(this));
HelpAdapter adapter = new HelpAdapter();
webView = findViewById(R.id.webview);
/* Placeholder only */
int[] questions = {
R.string.help_question1,
R.string.help_question2,
R.string.help_question3,
R.string.help_question4,
R.string.help_question5,
R.string.help_question6,
R.string.help_question7,
R.string.help_question8
};
int[] answers = {
R.string.what_is_eth,
R.string.why_alphawallet_eth,
R.string.how_i_get_money,
R.string.what_is_seed_phrase,
R.string.how_i_transfer_into_wallet,
R.string.tokenscript_explaination,
R.string.privacy_policy,
R.string.terms_of_service
};
adapter.setWebView(webView);
List<HelpItem> helpItems = new ArrayList<>();
for (int i = 0; i < questions.length; i++) {
if (isRawResource(answers[i]))
helpItems.add(new HelpItem(getString(questions[i]), answers[i]));
else if (getString(questions[i]).length() > 0)
helpItems.add(new HelpItem(getString(questions[i]), getString(answers[i])));
}
adapter.setHelpItems(helpItems);
list.setAdapter(adapter);
final LinearLayout contactUs = findViewById(R.id.layout_contact);
contactUs.setOnClickListener(v -> {
helpIntent();
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (hideWebView()) {
super.onOptionsItemSelected(item);
}
}
return true;
}
@Override
public void onBackPressed() {
if (hideWebView()) {
super.onBackPressed();
}
}
private boolean hideWebView() {
if (webView.getVisibility() == View.VISIBLE) {
webView.setVisibility(View.GONE);
return false;
}
return true;
}
private void helpIntent() {
final String at = "@";
String uriText =
"mailto:" + MediaLinks.AWALLET_EMAIL1 + at + MediaLinks.AWALLET_EMAIL2 +
"?subject=" + Uri.encode(MediaLinks.AWALLET_SUBJECT) +
"&body=" + Uri.encode("");
Uri uri = Uri.parse(uriText);
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(uri);
startActivity(Intent.createChooser(emailIntent, "Send email"));
}
public void onClick(View v) {
/*
// Create an instance of CognitoCachingCredentialsProvider
CognitoCachingCredentialsProvider cognitoProvider = new CognitoCachingCredentialsProvider(
this.getApplicationContext(), "cn-north-1:44edb8ae-67c1-40de-b70d-ae9db5581e6e", Regions.CN_NORTH_1);
// Create LambdaInvokerFactory, to be used to instantiate the Lambda proxy.
LambdaInvokerFactory factory = new LambdaInvokerFactory(this.getApplicationContext(),
Regions.CN_NORTH_1, cognitoProvider);
// Create the Lambda proxy object with a default Json data binder.
// You can provide your own data binder by implementing
// LambdaDataBinder.
final TrustAddressGenerator AWSLambdaInterface = factory.build(TrustAddressGenerator.class);
com.alphawallet.token.tools.TrustAddressGenerator.Request request = new com.alphawallet.token.tools.TrustAddressGenerator.Request("0x63cCEF733a093E5Bd773b41C96D3eCE361464942", "z+I6NxdALVtlc3TuUo2QEeV9rwyAmKB4UtQWkTLQhpE=");
// The Lambda function invocation results in a network call.
// Make sure it is not called from the main thread.
new AsyncTask<com.alphawallet.token.tools.TrustAddressGenerator.Request, Void, com.alphawallet.token.tools.TrustAddressGenerator.Response>() {
@Override
protected com.alphawallet.token.tools.TrustAddressGenerator.Response doInBackground(com.alphawallet.token.tools.TrustAddressGenerator.Request... params) {
// invoke the lambda method. In case it fails, it will throw a
// LambdaFunctionException.
try {
return AWSLambdaInterface.DeriveTrustAddress(params[0]);
} catch (LambdaFunctionException lfe) {
// please don't ignore such exception in production code!!
Log.e("Tag", "Failed to invoke AWS Lambda" + lfe.getDetails(), lfe);
return null;
}
}
@Override
protected void onPostExecute(com.alphawallet.token.tools.TrustAddressGenerator.Response response) {
if (response == null) {
return;
}
// Do a toast
Toast.makeText(HelpActivity.this, response.getTrustAddress(), Toast.LENGTH_LONG).show();
}
}.execute(request);*/
}
private boolean isRawResource(@RawRes int rawRes) {
try {
InputStream in = getResources().openRawResource(rawRes);
if (in.available() > 0) {
in.close();
return true;
}
in.close();
} catch (Exception ex) {
Timber.tag("READ_JS_TAG").d(ex, "Ex");
}
return false;
}
}

@ -21,14 +21,12 @@ import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
@ -93,7 +91,6 @@ import java.net.URLDecoder;
import java.util.List;
import dagger.hilt.android.AndroidEntryPoint;
import timber.log.Timber;
@AndroidEntryPoint
@ -221,19 +218,23 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
viewPager.setUserInputEnabled(false); // i think this replicates lockPages(true)
viewPager.setAdapter(pager2Adapter);
viewPager.setOffscreenPageLimit(WalletPage.values().length);
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback()
{
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
@Override
public void onPageSelected(int position) {
public void onPageSelected(int position)
{
super.onPageSelected(position);
}
@Override
public void onPageScrollStateChanged(int state) {
public void onPageScrollStateChanged(int state)
{
super.onPageScrollStateChanged(state);
}
});
@ -253,7 +254,8 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
}
KeyboardVisibilityEvent.setEventListener(
this, isOpen -> {
this, isOpen ->
{
if (isOpen)
{
setNavBarVisibility(View.GONE);
@ -300,7 +302,7 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
checkIntents(importData, importPath, intent);
}
Intent i = new Intent(this, PriceAlertsService.class);
startService(i);
}
@ -309,21 +311,24 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
{
//TODO: Move all fragment comms to this model - see all instances of ((HomeActivity)getActivity()).
getSupportFragmentManager()
.setFragmentResultListener(RESET_TOKEN_SERVICE, this, (requestKey, b) -> {
.setFragmentResultListener(RESET_TOKEN_SERVICE, this, (requestKey, b) ->
{
viewModel.restartTokensService();
//trigger wallet adapter reset
resetTokens();
});
getSupportFragmentManager()
.setFragmentResultListener(RESET_WALLET, this, (requestKey, b) -> {
.setFragmentResultListener(RESET_WALLET, this, (requestKey, b) ->
{
viewModel.restartTokensService();
resetTokens();
showPage(WALLET);
});
getSupportFragmentManager()
.setFragmentResultListener(CHANGE_CURRENCY, this, (k, b) -> {
.setFragmentResultListener(CHANGE_CURRENCY, this, (k, b) ->
{
resetTokens();
showPage(WALLET);
});
@ -332,7 +337,8 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
.setFragmentResultListener(RESET_TOOLBAR, this, (requestKey, b) -> invalidateOptionsMenu());
getSupportFragmentManager()
.setFragmentResultListener(ADDED_TOKEN, this, (requestKey, b) -> {
.setFragmentResultListener(ADDED_TOKEN, this, (requestKey, b) ->
{
List<ContractLocator> contractList = b.getParcelableArrayList(ADDED_TOKEN);
if (contractList != null)
{
@ -344,7 +350,8 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
.setFragmentResultListener(SHOW_BACKUP, this, (requestKey, b) -> showBackupWalletDialog(b.getBoolean(SHOW_BACKUP, false)));
getSupportFragmentManager()
.setFragmentResultListener(C.HANDLE_BACKUP, this, (requestKey, b) -> {
.setFragmentResultListener(C.HANDLE_BACKUP, this, (requestKey, b) ->
{
if (b.getBoolean(C.HANDLE_BACKUP))
{
backupWalletSuccess(b.getString("Key"));
@ -356,18 +363,21 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
});
getSupportFragmentManager()
.setFragmentResultListener(C.TOKEN_CLICK, this, (requestKey, b) -> {
.setFragmentResultListener(C.TOKEN_CLICK, this, (requestKey, b) ->
{
tokenClicked = true;
handler.postDelayed(() -> tokenClicked = false, 10000);
});
getSupportFragmentManager()
.setFragmentResultListener(CHANGED_LOCALE, this, (requestKey, b) -> {
.setFragmentResultListener(CHANGED_LOCALE, this, (requestKey, b) ->
{
viewModel.restartHomeActivity(getApplicationContext());
});
getSupportFragmentManager()
.setFragmentResultListener(SETTINGS_INSTANTIATED, this, (k, b) -> {
.setFragmentResultListener(SETTINGS_INSTANTIATED, this, (k, b) ->
{
loadingComplete();
});
}
@ -413,7 +423,8 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
successOverlay = findViewById(R.id.layout_success_overlay);
successImage = findViewById(R.id.success_image);
successOverlay.setOnClickListener(view -> {
successOverlay.setOnClickListener(view ->
{
//dismiss big green tick
successOverlay.setVisibility(View.GONE);
});
@ -426,20 +437,31 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
//check if wallet was imported - in which case no need to display
if (!walletImported)
{
int lighterBackground = Color.argb(102, 0, 0, 0); //40% opacity
int background = ContextCompat.getColor(getApplicationContext(), R.color.translucent_dark);
int statusBarColor = getWindow().getStatusBarColor();
backupWalletDialog = TutoShowcase.from(this);
backupWalletDialog.setContentView(R.layout.showcase_backup_wallet)
.setBackgroundColor(lighterBackground)
.onClickContentView(R.id.btn_close, view -> {
.setBackgroundColor(background)
.onClickContentView(R.id.btn_close, view ->
{
getWindow().setStatusBarColor(statusBarColor);
backupWalletDialog.dismiss();
})
.onClickContentView(R.id.showcase_layout, view ->
{
getWindow().setStatusBarColor(statusBarColor);
backupWalletDialog.dismiss();
})
.on(R.id.settings_tab)
.addCircle()
.onClick(v -> {
.onClick(v ->
{
getWindow().setStatusBarColor(statusBarColor);
backupWalletDialog.dismiss();
showPage(SETTINGS);
})
.show();
});
backupWalletDialog.show();
getWindow().setStatusBarColor(background);
}
viewModel.setFindWalletAddressDialogShown(true);
}
@ -478,7 +500,8 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
}
initViews();
handler.post(() -> {
handler.post(() ->
{
//check clipboard
String magicLink = ImportTokenActivity.getMagiclinkFromClipboard(this);
if (magicLink != null)
@ -564,7 +587,8 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
@Override
public void onDestroy()
{
if (getSelectedItem() != null) viewModel.storeCurrentFragmentId(getSelectedItem().ordinal());
if (getSelectedItem() != null)
viewModel.storeCurrentFragmentId(getSelectedItem().ordinal());
super.onDestroy();
viewModel.onClean();
if (homeReceiver != null)
@ -656,7 +680,8 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
cDialog.setCancelable(true);
cDialog.setSmallText("Using an old version of Alphawallet. Please update from the Play Store or Alphawallet website.");
cDialog.setPrimaryButtonText(R.string.ok);
cDialog.setPrimaryButtonListener(v -> {
cDialog.setPrimaryButtonListener(v ->
{
cDialog.dismiss();
});
dialog = cDialog;
@ -684,14 +709,16 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
{
handler.removeCallbacksAndMessages(null); //remove any previous error call, only use final error
// This is in a runnable because the error will come from non main thread process
handler.postDelayed(() -> {
handler.postDelayed(() ->
{
hideDialog();
AWalletAlertDialog aDialog = new AWalletAlertDialog(this);
aDialog.setTitle(getString(R.string.tokenscript_file_error));
aDialog.setMessage(message);
aDialog.setIcon(AWalletAlertDialog.ERROR);
aDialog.setButtonText(R.string.button_ok);
aDialog.setButtonListener(v -> {
aDialog.setButtonListener(v ->
{
aDialog.dismiss();
});
dialog = aDialog;
@ -802,13 +829,15 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
private class ScreenSlidePagerAdapter extends FragmentStateAdapter
{
public ScreenSlidePagerAdapter(@NonNull FragmentActivity fragmentActivity) {
public ScreenSlidePagerAdapter(@NonNull FragmentActivity fragmentActivity)
{
super(fragmentActivity);
}
@NonNull
@Override
public Fragment createFragment(int position) {
public Fragment createFragment(int position)
{
switch (WalletPage.values()[position])
{
case WALLET:
@ -829,7 +858,8 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
}
@Override
public int getItemCount() {
public int getItemCount()
{
return WalletPage.values().length;
}
@ -844,13 +874,13 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
{
default:
case WALLET:
return (BaseFragment)walletFragment;
return (BaseFragment) walletFragment;
case ACTIVITY:
return (BaseFragment)activityFragment;
return (BaseFragment) activityFragment;
case DAPP_BROWSER:
return (BaseFragment)dappBrowserFragment;
return (BaseFragment) dappBrowserFragment;
case SETTINGS:
return (BaseFragment)settingsFragment;
return (BaseFragment) settingsFragment;
}
}
else return (BaseFragment) getSupportFragmentManager().getFragments().get(page.ordinal());
@ -870,7 +900,8 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
String newBuild = "New version: " + build;
dialog.setMediumText(newBuild);
dialog.setPrimaryButtonText(R.string.confirm_update);
dialog.setPrimaryButtonListener(v -> {
dialog.setPrimaryButtonListener(v ->
{
if (checkWritePermission(RC_DOWNLOAD_EXTERNAL_WRITE_PERM))
{
viewModel.downloadAndInstall(build, this);
@ -885,7 +916,8 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
{
dialog.setSecondaryButtonText(R.string.dialog_later);
}
dialog.setSecondaryButtonListener(v -> {
dialog.setSecondaryButtonListener(v ->
{
//only dismiss twice before we stop warning.
viewModel.setUpdateAsksCount(asks);
dialog.dismiss();
@ -1023,7 +1055,11 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
boolean hasPermission = true;
for (int i = 0; i < permissions.length; i++)
{
if (grantResults[i] == -1) { hasPermission = false; break; }
if (grantResults[i] == -1)
{
hasPermission = false;
break;
}
}
return hasPermission;
@ -1036,7 +1072,8 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
aDialog.setTitle(R.string.install_error);
aDialog.setMessage(R.string.require_write_permission);
aDialog.setButtonText(R.string.action_cancel);
aDialog.setButtonListener(v -> {
aDialog.setButtonListener(v ->
{
aDialog.dismiss();
});
aDialog.show();
@ -1134,7 +1171,7 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
if (data != null && resultCode == Activity.RESULT_OK && data.hasExtra(C.DAPP_URL_LOAD))
{
((DappBrowserFragment) getFragment(DAPP_BROWSER)).switchNetworkAndLoadUrl(data.getLongExtra(C.EXTRA_CHAIN_ID, MAINNET_ID),
data.getStringExtra(C.DAPP_URL_LOAD));
data.getStringExtra(C.DAPP_URL_LOAD));
showPage(DAPP_BROWSER);
}
else if (data != null && resultCode == Activity.RESULT_OK && data.hasExtra(C.EXTRA_TXHASH))
@ -1221,14 +1258,16 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick
viewModel.actionSheetConfirm(mode);
}
private void hideSystemUI() {
private void hideSystemUI()
{
WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
WindowInsetsControllerCompat inset = new WindowInsetsControllerCompat(getWindow(), getWindow().getDecorView());
inset.setSystemBarsBehavior(BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
inset.hide(WindowInsetsCompat.Type.statusBars() | WindowInsetsCompat.Type.navigationBars());
}
private void showSystemUI() {
private void showSystemUI()
{
WindowCompat.setDecorFitsSystemWindows(getWindow(), true);
WindowInsetsControllerCompat inset = new WindowInsetsControllerCompat(getWindow(), getWindow().getDecorView());
inset.show(WindowInsetsCompat.Type.statusBars() | WindowInsetsCompat.Type.navigationBars());

@ -196,17 +196,17 @@ public class ImportSeedFragment extends ImportFragment implements OnSuggestionCl
}
if (passwordPhraseCounter.match()) {
wordCount.setTextColor(ContextCompat.getColor(requireActivity(), R.color.nasty_green));
wordCount.setTextColor(ContextCompat.getColor(requireActivity(), R.color.positive));
wordCount.setTypeface(boldTypeface);
updateButtonState(true);
} else if (passwordPhraseCounter.notEnough())
{
wordCount.setTextColor(ContextCompat.getColor(requireActivity(), R.color.colorPrimaryDark));
wordCount.setTextColor(ContextCompat.getColor(requireActivity(), R.color.text_secondary));
wordCount.setTypeface(normalTypeface);
updateButtonState(false);
} else if (passwordPhraseCounter.exceed())
{
wordCount.setTextColor(ContextCompat.getColor(requireActivity(), R.color.dark_seed_danger));
wordCount.setTextColor(ContextCompat.getColor(requireActivity(), R.color.error));
updateButtonState(false);
}

@ -96,7 +96,7 @@ public class ImportWalletActivity extends BaseActivity implements OnImportSeedLi
pages.add(ImportType.SEED_FORM_INDEX.ordinal(), new Pair<>(getString(R.string.tab_seed), ImportSeedFragment.create()));
pages.add(ImportType.KEYSTORE_FORM_INDEX.ordinal(), new Pair<>(getString(R.string.tab_keystore), ImportKeystoreFragment.create()));
pages.add(ImportType.PRIVATE_KEY_FORM_INDEX.ordinal(), new Pair<>(getString(R.string.tab_private_key), ImportPrivateKeyFragment.create()));
if (isWatch) pages.add(ImportType.WATCH_FORM_INDEX.ordinal(), new Pair<>(getString(R.string.watch_wallet), SetWatchWalletFragment.create()));
pages.add(ImportType.WATCH_FORM_INDEX.ordinal(), new Pair<>(getString(R.string.watch_wallet), SetWatchWalletFragment.create()));
ViewPager2 viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(new TabPagerAdapter(this, pages));

@ -64,10 +64,7 @@ public class MyAddressActivity extends BaseActivity implements AmountReadyCallba
private String displayName;
private Token token;
private ImageView qrImageView;
private TextView titleView;
private TextView address;
private LinearLayout layoutInputAmount;
private LinearLayout selectAddress;
private NetworkInfo networkInfo;
private AddressMode currentMode = AddressMode.MODE_ADDRESS;
private long overrideNetwork;
@ -111,13 +108,9 @@ public class MyAddressActivity extends BaseActivity implements AmountReadyCallba
private void initViews() {
toolbar();
titleView = findViewById(R.id.title_my_address);
layoutInputAmount = findViewById(R.id.layout_define_request);
selectAddress = findViewById(R.id.layout_select_address);
address = findViewById(R.id.address);
qrImageView = findViewById(R.id.qr_image);
selectAddress = findViewById(R.id.layout_select_address);
qrImageView.setBackgroundResource(R.color.white);
qrImageView.setBackgroundResource(R.color.surface);
ensFetchProgressBar = findViewById(R.id.ens_fetch_progress);
if (viewModel == null) initViewModel();
@ -209,12 +202,9 @@ public class MyAddressActivity extends BaseActivity implements AmountReadyCallba
initViews();
findViewById(R.id.toolbar_title).setVisibility(View.GONE);
setTitle("");
titleView.setVisibility(View.VISIBLE);
displayAddress = Keys.toChecksumAddress(wallet.address);
networkInfo = viewModel.getEthereumNetworkRepository().getNetworkByChain(overrideNetwork);
currentMode = AddressMode.MODE_POS;
address.setVisibility(View.GONE);
selectAddress.setVisibility(View.GONE);
layoutInputAmount.setVisibility(View.VISIBLE);
amountInput = findViewById(R.id.input_amount);

@ -41,6 +41,7 @@ import com.alphawallet.app.ui.widget.divider.ItemOffsetDecoration;
import com.alphawallet.app.ui.widget.divider.ListDivider;
import com.alphawallet.app.viewmodel.NFTAssetsViewModel;
import com.alphawallet.ethereum.EthereumNetworkBase;
import com.google.android.material.color.MaterialColors;
import java.math.BigInteger;
import java.util.List;
@ -145,7 +146,7 @@ public class NFTAssetsFragment extends BaseFragment implements OnAssetClickListe
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
recyclerView.removeItemDecoration(listItemDecoration);
recyclerView.addItemDecoration(gridItemDecoration);
recyclerView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
recyclerView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.surface));
initAndAttachAdapter(true);
}

@ -4,8 +4,10 @@ package com.alphawallet.app.ui;
import static android.app.Activity.RESULT_OK;
import static com.alphawallet.app.C.CHANGED_LOCALE;
import static com.alphawallet.app.C.CHANGE_CURRENCY;
import static com.alphawallet.app.C.EXTRA_CURRENCY;
import static com.alphawallet.app.C.EXTRA_LOCALE;
import static com.alphawallet.app.C.EXTRA_STATE;
import static com.alphawallet.app.C.Key.WALLET;
import static com.alphawallet.app.C.RESET_TOOLBAR;
import static com.alphawallet.app.C.RESET_WALLET;
import static com.alphawallet.app.C.SETTINGS_INSTANTIATED;
import static com.alphawallet.app.entity.BackupOperationType.BACKUP_HD_KEY;
@ -16,6 +18,7 @@ import static com.alphawallet.token.tools.TokenDefinition.TOKENSCRIPT_CURRENT_SC
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@ -45,15 +48,17 @@ import com.alphawallet.app.util.UpdateUtils;
import com.alphawallet.app.viewmodel.NewSettingsViewModel;
import com.alphawallet.app.widget.NotificationView;
import com.alphawallet.app.widget.SettingsItemView;
import com.google.android.material.card.MaterialCardView;
import java.util.Locale;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
@AndroidEntryPoint
public class NewSettingsFragment extends BaseFragment {
public class NewSettingsFragment extends BaseFragment
{
private NewSettingsViewModel viewModel;
@ -65,9 +70,12 @@ public class NewSettingsFragment extends BaseFragment {
private SettingsItemView changeWalletSetting;
private SettingsItemView backUpWalletSetting;
private SettingsItemView notificationsSetting;
private SettingsItemView changeLanguage;
private SettingsItemView changeCurrency;
private SettingsItemView biometricsSetting;
private SettingsItemView selectNetworksSetting;
private SettingsItemView advancedSetting;
private SettingsItemView darkModeSetting;
private SettingsItemView supportSetting;
private SettingsItemView walletConnectSetting;
private SettingsItemView showSeedPhrase;
@ -81,14 +89,27 @@ public class NewSettingsFragment extends BaseFragment {
private ImageView backupMenuButton;
private View backupPopupAnchor;
private NotificationView notificationView;
private MaterialCardView updateLayout;
private int pendingUpdate = 0;
private LinearLayout updateLayout;
private Wallet wallet;
ActivityResultLauncher<Intent> updateLocale = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result ->
{
updateLocale(result.getData());
});
ActivityResultLauncher<Intent> updateCurrency = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result ->
{
updateCurrency(result.getData());
});
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
viewModel = new ViewModelProvider(this)
.get(NewSettingsViewModel.class);
viewModel.defaultWallet().observe(getViewLifecycleOwner(), this::onDefaultWallet);
@ -118,13 +139,17 @@ public class NewSettingsFragment extends BaseFragment {
return view;
}
private void initNotificationView(View view) {
private void initNotificationView(View view)
{
notificationView = view.findViewById(R.id.notification);
if (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
if (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.M)
{
notificationView.setNotificationBackgroundColor(R.color.indigo);
notificationView.setTitle(getContext().getString(R.string.title_version_support_warning));
notificationView.setMessage(getContext().getString(R.string.message_version_support_warning));
} else {
}
else
{
notificationView.setVisibility(View.GONE);
}
}
@ -136,7 +161,8 @@ public class NewSettingsFragment extends BaseFragment {
checkPendingUpdate(getView());
}
private void initBackupWarningViews(View view) {
private void initBackupWarningViews(View view)
{
layoutBackup = view.findViewById(R.id.layout_item_warning);
backupTitle = view.findViewById(R.id.text_title);
backupDetail = view.findViewById(R.id.text_detail);
@ -147,7 +173,8 @@ public class NewSettingsFragment extends BaseFragment {
warningSeparator = view.findViewById(R.id.warning_separator);
}
private void initializeSettings(View view) {
private void initializeSettings(View view)
{
walletSettingsLayout = view.findViewById(R.id.layout_settings_wallet);
systemSettingsLayout = view.findViewById(R.id.layout_settings_system);
supportSettingsLayout = view.findViewById(R.id.layout_settings_support);
@ -201,6 +228,18 @@ public class NewSettingsFragment extends BaseFragment {
.withListener(this::onNotificationsSettingClicked)
.build();
changeLanguage = new SettingsItemView.Builder(getContext())
.withIcon(R.drawable.ic_settings_language)
.withTitle(R.string.title_change_language)
.withListener(this::onChangeLanguageClicked)
.build();
changeCurrency = new SettingsItemView.Builder(getContext())
.withIcon(R.drawable.ic_currency)
.withTitle(R.string.settings_locale_currency)
.withListener(this::onChangeCurrencyClicked)
.build();
// biometricsSetting =
// new SettingsItemView.Builder(getContext())
// .withType(SettingsItemView.Type.TOGGLE)
@ -223,6 +262,13 @@ public class NewSettingsFragment extends BaseFragment {
.withListener(this::onAdvancedSettingClicked)
.build();
darkModeSetting =
new SettingsItemView.Builder(getContext())
.withIcon(R.drawable.ic_settings_darkmode)
.withTitle(R.string.title_dark_mode)
.withListener(this::onDarkModeSettingClicked)
.build();
supportSetting =
new SettingsItemView.Builder(getContext())
.withIcon(R.drawable.ic_settings_support)
@ -231,7 +277,8 @@ public class NewSettingsFragment extends BaseFragment {
.build();
}
private void addSettingsToLayout() {
private void addSettingsToLayout()
{
int walletIndex = 0;
int systemIndex = 0;
int supportIndex = 0;
@ -250,19 +297,27 @@ public class NewSettingsFragment extends BaseFragment {
walletSettingsLayout.addView(walletConnectSetting, walletIndex++);
if (CustomViewSettings.getLockedChains().size() == 0)
systemSettingsLayout.addView(selectNetworksSetting, systemIndex++);
if (biometricsSetting != null)
systemSettingsLayout.addView(biometricsSetting, systemIndex++);
systemSettingsLayout.addView(notificationsSetting, systemIndex++);
if (biometricsSetting != null) systemSettingsLayout.addView(biometricsSetting, systemIndex++);
systemSettingsLayout.addView(changeLanguage, systemIndex++);
if (CustomViewSettings.getLockedChains().size() == 0)
systemSettingsLayout.addView(selectNetworksSetting, systemIndex++);
systemSettingsLayout.addView(changeCurrency, systemIndex++);
systemSettingsLayout.addView(darkModeSetting, systemIndex++);
systemSettingsLayout.addView(advancedSetting, systemIndex++);
supportSettingsLayout.addView(supportSetting, supportIndex++);
}
private void setInitialSettingsData(View view) {
private void setInitialSettingsData(View view)
{
TextView appVersionText = view.findViewById(R.id.text_version);
appVersionText.setText(String.format(Locale.getDefault(), "%s (%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE));
TextView tokenScriptVersionText = view.findViewById(R.id.text_tokenscript_compatibility);
@ -281,7 +336,8 @@ public class NewSettingsFragment extends BaseFragment {
}
ActivityResultLauncher<Intent> handleBackupClick = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
result ->
{
String keyBackup = "";
boolean noLockScreen = false;
Intent data = result.getData();
@ -295,7 +351,8 @@ public class NewSettingsFragment extends BaseFragment {
getParentFragmentManager().setFragmentResult(C.HANDLE_BACKUP, b);
});
private void openBackupActivity(Wallet wallet) {
private void openBackupActivity(Wallet wallet)
{
Intent intent = new Intent(getContext(), BackupFlowActivity.class);
intent.putExtra(WALLET, wallet);
@ -329,7 +386,8 @@ public class NewSettingsFragment extends BaseFragment {
handleBackupClick.launch(intent);
}
private void onDefaultWallet(Wallet wallet) {
private void onDefaultWallet(Wallet wallet)
{
this.wallet = wallet;
if (wallet.address != null)
{
@ -343,14 +401,18 @@ public class NewSettingsFragment extends BaseFragment {
}
}
switch (wallet.authLevel) {
switch (wallet.authLevel)
{
case NOT_SET:
case STRONGBOX_NO_AUTHENTICATION:
case TEE_NO_AUTHENTICATION:
if (wallet.lastBackupTime > 0) {
if (wallet.lastBackupTime > 0)
{
backUpWalletSetting.setTitle(getString(R.string.action_upgrade_key));
backUpWalletSetting.setSubtitle(getString(R.string.not_locked));
} else {
}
else
{
backUpWalletSetting.setTitle(getString(R.string.back_up_this_wallet));
backUpWalletSetting.setSubtitle(getString(R.string.back_up_now));
}
@ -379,14 +441,21 @@ public class NewSettingsFragment extends BaseFragment {
case KEYSTORE_LEGACY:
break;
}
viewModel.setLocale(getContext());
changeLanguage.setSubtitle(LocaleUtils.getDisplayLanguage(viewModel.getActiveLocale(), viewModel.getActiveLocale()));
changeCurrency.setSubtitle(viewModel.getDefaultCurrency());
}
@Override
public void onResume() {
public void onResume()
{
super.onResume();
if (viewModel == null)
{
((HomeActivity)getActivity()).resetFragment(WalletPage.SETTINGS);
((HomeActivity) getActivity()).resetFragment(WalletPage.SETTINGS);
}
else
{
@ -394,7 +463,8 @@ public class NewSettingsFragment extends BaseFragment {
}
}
public void backupSeedSuccess(boolean hasNoLock) {
public void backupSeedSuccess(boolean hasNoLock)
{
if (viewModel != null) viewModel.TestWalletBackup();
if (layoutBackup != null) layoutBackup.setVisibility(View.GONE);
if (hasNoLock)
@ -403,11 +473,16 @@ public class NewSettingsFragment extends BaseFragment {
}
}
private void backupWarning(String s) {
if (s.equals(viewModel.defaultWallet().getValue().address)) {
private void backupWarning(String s)
{
if (s.equals(viewModel.defaultWallet().getValue().address))
{
addBackupNotice(GenericWalletInteract.BackupLevel.WALLET_HAS_HIGH_VALUE);
} else {
if (layoutBackup != null) {
}
else
{
if (layoutBackup != null)
{
layoutBackup.setVisibility(View.GONE);
}
//remove the number prompt
@ -417,32 +492,37 @@ public class NewSettingsFragment extends BaseFragment {
}
}
void addBackupNotice(GenericWalletInteract.BackupLevel walletValue) {
void addBackupNotice(GenericWalletInteract.BackupLevel walletValue)
{
layoutBackup.setVisibility(View.VISIBLE);
warningSeparator.setVisibility(View.VISIBLE);
if (wallet != null) {
if (wallet != null)
{
backupButton.setText(getString(R.string.back_up_wallet_action, wallet.address.substring(0, 5)));
backupButton.setOnClickListener(v -> openBackupActivity(wallet));
backupTitle.setText(getString(R.string.wallet_not_backed_up));
layoutBackup.setBackgroundResource(R.drawable.background_warning_red_8dp);
backupDetail.setText(getString(R.string.backup_wallet_detail));
backupMenuButton.setOnClickListener(v -> {
backupMenuButton.setOnClickListener(v ->
{
showPopup(backupPopupAnchor, wallet.address);
});
if (getActivity() != null) {
if (getActivity() != null)
{
((HomeActivity) getActivity()).addSettingsBadgeKey(C.KEY_NEEDS_BACKUP);
}
}
}
private void showPopup(View view, String walletAddress) {
private void showPopup(View view, String walletAddress)
{
LayoutInflater inflater = LayoutInflater.from(getContext());
View popupView = inflater.inflate(R.layout.popup_remind_later, null);
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, true);
popupView.setOnClickListener(v -> {
popupView.setOnClickListener(v ->
{
viewModel.setIsDismissed(walletAddress, true);
backedUp(walletAddress);
popupWindow.dismiss();
@ -450,24 +530,29 @@ public class NewSettingsFragment extends BaseFragment {
popupWindow.showAsDropDown(view, 0, 0);
}
private void backedUp(String walletAddress) {
private void backedUp(String walletAddress)
{
layoutBackup.setVisibility(View.GONE);
warningSeparator.setVisibility(View.GONE);
if (getActivity() != null)
((HomeActivity) getActivity()).postponeWalletBackupWarning(walletAddress);
}
private void onShowWalletAddressSettingClicked() {
private void onShowWalletAddressSettingClicked()
{
viewModel.showMyAddress(getContext());
}
private void onChangeWalletSettingClicked() {
private void onChangeWalletSettingClicked()
{
viewModel.showManageWallets(getContext(), false);
}
private void onBackUpWalletSettingClicked() {
private void onBackUpWalletSettingClicked()
{
Wallet wallet = viewModel.defaultWallet().getValue();
if (wallet != null) {
if (wallet != null)
{
openBackupActivity(wallet);
}
}
@ -475,7 +560,8 @@ public class NewSettingsFragment extends BaseFragment {
private void onShowSeedPhrase()
{
Wallet wallet = viewModel.defaultWallet().getValue();
if (wallet != null) {
if (wallet != null)
{
openShowSeedPhrase(wallet);
}
}
@ -486,28 +572,33 @@ public class NewSettingsFragment extends BaseFragment {
requireActivity().startActivity(intent);
}
private void onNotificationsSettingClicked() {
private void onNotificationsSettingClicked()
{
viewModel.setNotificationState(notificationsSetting.getToggleState());
}
private void onBiometricsSettingClicked() {
private void onBiometricsSettingClicked()
{
// TODO: Implementation
}
ActivityResultLauncher<Intent> networkSettingsHandler = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
result ->
{
//send instruction to restart tokenService
getParentFragmentManager().setFragmentResult(RESET_TOKEN_SERVICE, new Bundle());
});
private void onSelectNetworksSettingClicked() {
private void onSelectNetworksSettingClicked()
{
Intent intent = new Intent(getActivity(), SelectNetworkFilterActivity.class);
intent.putExtra(C.EXTRA_SINGLE_ITEM, false);
networkSettingsHandler.launch(intent);
}
ActivityResultLauncher<Intent> advancedSettingsHandler = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
result ->
{
Intent data = result.getData();
if (data == null) return;
if (data.getBooleanExtra(RESET_WALLET, false))
@ -524,17 +615,26 @@ public class NewSettingsFragment extends BaseFragment {
}
});
private void onAdvancedSettingClicked() {
private void onAdvancedSettingClicked()
{
Intent intent = new Intent(getActivity(), AdvancedSettingsActivity.class);
advancedSettingsHandler.launch(intent);
}
private void onSupportSettingClicked() {
private void onDarkModeSettingClicked()
{
Intent intent = new Intent(getActivity(), SelectThemeActivity.class);
startActivity(intent);
}
private void onSupportSettingClicked()
{
Intent intent = new Intent(getActivity(), SupportSettingsActivity.class);
startActivity(intent);
}
private void onWalletConnectSettingClicked() {
private void onWalletConnectSettingClicked()
{
Intent intent = new Intent(getActivity(), WalletConnectSessionActivity.class);
intent.putExtra("wallet", wallet);
startActivity(intent);
@ -551,15 +651,18 @@ public class NewSettingsFragment extends BaseFragment {
TextView available = view.findViewById(R.id.text_detail_available);
current.setText(getString(R.string.installed_version, String.valueOf(BuildConfig.VERSION_CODE)));
available.setText(getString(R.string.available_version, String.valueOf(pendingUpdate)));
if (getActivity() != null) {
if (getActivity() != null)
{
((HomeActivity) getActivity()).addSettingsBadgeKey(C.KEY_UPDATE_AVAILABLE);
}
updateLayout.setOnClickListener(v -> {
updateLayout.setOnClickListener(v ->
{
UpdateUtils.pushUpdateDialog(getActivity());
updateLayout.setVisibility(View.GONE);
pendingUpdate = 0;
if (getActivity() != null) {
if (getActivity() != null)
{
((HomeActivity) getActivity()).removeSettingsBadgeKey(C.KEY_UPDATE_AVAILABLE);
}
});
@ -569,4 +672,52 @@ public class NewSettingsFragment extends BaseFragment {
updateLayout.setVisibility(View.GONE);
}
}
private void onChangeLanguageClicked()
{
Intent intent = new Intent(getActivity(), SelectLocaleActivity.class);
String selectedLocale = viewModel.getActiveLocale();
intent.putExtra(EXTRA_LOCALE, selectedLocale);
intent.putParcelableArrayListExtra(EXTRA_STATE, viewModel.getLocaleList(getContext()));
updateLocale.launch(intent);
}
private void onChangeCurrencyClicked()
{
Intent intent = new Intent(getActivity(), SelectCurrencyActivity.class);
String currentLocale = viewModel.getDefaultCurrency();
intent.putExtra(EXTRA_CURRENCY, currentLocale);
intent.putParcelableArrayListExtra(EXTRA_STATE, viewModel.getCurrencyList());
updateCurrency.launch(intent);
}
public void updateLocale(Intent data)
{
if (data != null)
{
String newLocale = data.getStringExtra(C.EXTRA_LOCALE);
String oldLocale = viewModel.getActiveLocale();
if (!TextUtils.isEmpty(newLocale) && !newLocale.equals(oldLocale))
{
viewModel.updateLocale(newLocale, getContext());
getActivity().recreate();
}
}
}
public void updateCurrency(Intent data)
{
if (data != null)
{
String currencyCode = data.getStringExtra(C.EXTRA_CURRENCY);
if (!viewModel.getDefaultCurrency().equals(currencyCode))
{
viewModel.updateCurrency(currencyCode)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(res -> getActivity().recreate())
.isDisposed();
}
}
}
}

@ -29,8 +29,6 @@ import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import static com.alphawallet.app.C.Key.TICKET_RANGE;
@ -49,7 +47,7 @@ public class RedeemAssetSelectActivity extends BaseActivity implements TokensAda
protected RedeemAssetSelectViewModel viewModel;
private SystemView systemView;
private ProgressView progressView;
private int currentMenu = R.menu.send_menu;
private int currentMenu = R.menu.menu_send;
private FinishReceiver finishReceiver;
@ -103,7 +101,7 @@ public class RedeemAssetSelectActivity extends BaseActivity implements TokensAda
private void setupRedeemSelector()
{
currentMenu = R.menu.send_menu;
currentMenu = R.menu.menu_send;
invalidateOptionsMenu();
RecyclerView list = findViewById(R.id.listTickets);
@ -112,7 +110,7 @@ public class RedeemAssetSelectActivity extends BaseActivity implements TokensAda
nextButton.setVisibility(View.GONE);
redeemButton.setVisibility(View.VISIBLE);
currentMenu = R.menu.redeem_menu;
currentMenu = R.menu.menu_redeem;
invalidateOptionsMenu();
list.setLayoutManager(new LinearLayoutManager(this));
@ -181,7 +179,7 @@ public class RedeemAssetSelectActivity extends BaseActivity implements TokensAda
@Override
public void onTokenClick(View v, Token token, List<BigInteger> ids, boolean selected) {
currentMenu = R.menu.redeem_menu;
currentMenu = R.menu.menu_redeem;
invalidateOptionsMenu();
}

@ -1,31 +0,0 @@
package com.alphawallet.app.ui;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.alphawallet.app.R;
public class SearchFragment extends Fragment {
private View.OnClickListener listener;
public void setCallbacks(View.OnClickListener listener) {
this.listener = listener;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search, container, false);
RelativeLayout layout = view.findViewById(R.id.layout);
layout.setOnClickListener(listener);
return view;
}
}

@ -2,9 +2,6 @@ package com.alphawallet.app.ui;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
@ -12,10 +9,15 @@ import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.alphawallet.app.C;
import com.alphawallet.app.R;
import com.alphawallet.app.entity.CurrencyItem;
import com.alphawallet.app.ui.widget.divider.ListDivider;
import com.google.android.material.radiobutton.MaterialRadioButton;
import java.util.ArrayList;
@ -24,11 +26,12 @@ import dagger.hilt.android.AndroidEntryPoint;
@AndroidEntryPoint
public class SelectCurrencyActivity extends BaseActivity {
private RecyclerView recyclerView;
private CustomAdapter adapter;
private SelectCurrencyAdapter adapter;
private String currentCurrency;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_list_activity);
toolbar();
@ -36,25 +39,31 @@ public class SelectCurrencyActivity extends BaseActivity {
currentCurrency = getIntent().getStringExtra(C.EXTRA_CURRENCY);
ArrayList<CurrencyItem> currencyItems = getIntent().getParcelableArrayListExtra(C.EXTRA_STATE);
if (currencyItems != null) {
if (currencyItems != null)
{
recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new CustomAdapter(currencyItems, currentCurrency);
adapter = new SelectCurrencyAdapter(currencyItems, currentCurrency);
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new ListDivider(this));
}
}
@Override
public void onBackPressed() {
if (!currentCurrency.equals(adapter.getSelectedItemId())) {
public void onBackPressed()
{
if (!currentCurrency.equals(adapter.getSelectedItemId()))
{
setCurrency();
} else {
}
else
{
super.onBackPressed();
}
}
private void setCurrency() {
private void setCurrency()
{
Intent intent = new Intent();
String item = adapter.getSelectedItemId();
intent.putExtra(C.EXTRA_CURRENCY, item);
@ -63,69 +72,62 @@ public class SelectCurrencyActivity extends BaseActivity {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
public class SelectCurrencyAdapter extends RecyclerView.Adapter<SelectCurrencyAdapter.SelectCurrencyViewHolder> {
private final ArrayList<CurrencyItem> dataSet;
private String selectedItemId;
private void setSelectedItemId(String selectedItemId) {
private SelectCurrencyAdapter(ArrayList<CurrencyItem> data, String selectedItemId)
{
this.dataSet = data;
this.selectedItemId = selectedItemId;
for (CurrencyItem l : data)
{
if (l.getCode().equals(selectedItemId))
{
l.setSelected(true);
}
}
}
private String getSelectedItemId() {
private String getSelectedItemId()
{
return this.selectedItemId;
}
private void setSelectedItemId(String selectedItemId)
{
this.selectedItemId = selectedItemId;
}
@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
public SelectCurrencyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_currency, parent, false);
return new CustomViewHolder(itemView);
}
class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView checkbox;
ImageView flag;
TextView code;
TextView name;
View itemLayout;
CustomViewHolder(View view) {
super(view);
checkbox = view.findViewById(R.id.checkbox);
flag = view.findViewById(R.id.flag);
code = view.findViewById(R.id.code);
name = view.findViewById(R.id.name);
itemLayout = view.findViewById(R.id.layout_list_item);
}
}
private CustomAdapter(ArrayList<CurrencyItem> data, String selectedItemId) {
this.dataSet = data;
this.selectedItemId = selectedItemId;
for (CurrencyItem l : data) {
if (l.getCode().equals(selectedItemId)) {
l.setSelected(true);
}
}
return new SelectCurrencyViewHolder(itemView);
}
@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
public void onBindViewHolder(SelectCurrencyViewHolder holder, int position)
{
CurrencyItem currencyItem = dataSet.get(position);
holder.name.setText(currencyItem.getName());
holder.code.setText(currencyItem.getCode());
holder.flag.setImageResource(currencyItem.getFlag());
holder.itemLayout.setOnClickListener(v -> {
for (int i = 0; i < dataSet.size(); i++) {
for (int i = 0; i < dataSet.size(); i++)
{
dataSet.get(i).setSelected(false);
}
dataSet.get(position).setSelected(true);
@ -133,12 +135,31 @@ public class SelectCurrencyActivity extends BaseActivity {
notifyDataSetChanged();
});
holder.checkbox.setSelected(currencyItem.isSelected());
holder.radioButton.setChecked(currencyItem.isSelected());
}
@Override
public int getItemCount() {
public int getItemCount()
{
return dataSet.size();
}
class SelectCurrencyViewHolder extends RecyclerView.ViewHolder {
MaterialRadioButton radioButton;
ImageView flag;
TextView code;
TextView name;
View itemLayout;
SelectCurrencyViewHolder(View view)
{
super(view);
radioButton = view.findViewById(R.id.radio_button);
flag = view.findViewById(R.id.flag);
code = view.findViewById(R.id.code);
name = view.findViewById(R.id.name);
itemLayout = view.findViewById(R.id.layout_list_item);
}
}
}
}

@ -2,33 +2,36 @@ package com.alphawallet.app.ui;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.alphawallet.app.C;
import com.alphawallet.app.R;
import com.alphawallet.app.entity.LocaleItem;
import com.alphawallet.app.ui.widget.divider.ListDivider;
import com.google.android.material.radiobutton.MaterialRadioButton;
import java.util.ArrayList;
import dagger.hilt.android.AndroidEntryPoint;
@AndroidEntryPoint
public class SelectLocaleActivity extends BaseActivity {
public class SelectLocaleActivity extends BaseActivity
{
private RecyclerView recyclerView;
private CustomAdapter adapter;
private String currentLocale;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_list_activity);
toolbar();
@ -38,7 +41,8 @@ public class SelectLocaleActivity extends BaseActivity {
ArrayList<LocaleItem> localeItems = getIntent().getParcelableArrayListExtra(C.EXTRA_STATE);
if (localeItems != null) {
if (localeItems != null)
{
recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new CustomAdapter(localeItems, currentLocale);
@ -47,7 +51,8 @@ public class SelectLocaleActivity extends BaseActivity {
}
}
private void setLocale(String id) {
private void setLocale(String id)
{
Intent intent = new Intent();
intent.putExtra(C.EXTRA_LOCALE, id);
setResult(RESULT_OK, intent);
@ -55,73 +60,91 @@ public class SelectLocaleActivity extends BaseActivity {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
public void onBackPressed()
{
String id = adapter.getSelectedItemId();
if (id != null && !id.equals(currentLocale)) {
if (id != null && !id.equals(currentLocale))
{
setLocale(id);
} else {
}
else
{
super.onBackPressed();
}
}
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder>
{
private final ArrayList<LocaleItem> dataSet;
private String selectedItemId;
private void setSelectedItemId(String selectedItemId) {
private void setSelectedItemId(String selectedItemId)
{
this.selectedItemId = selectedItemId;
}
private String getSelectedItemId() {
private String getSelectedItemId()
{
return this.selectedItemId;
}
@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_simple_radio, parent, false);
return new CustomViewHolder(itemView);
}
class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView checkbox;
class CustomViewHolder extends RecyclerView.ViewHolder
{
MaterialRadioButton radio;
TextView name;
View itemLayout;
CustomViewHolder(View view) {
CustomViewHolder(View view)
{
super(view);
checkbox = view.findViewById(R.id.checkbox);
radio = view.findViewById(R.id.radio);
name = view.findViewById(R.id.name);
itemLayout = view.findViewById(R.id.layout_list_item);
}
}
private CustomAdapter(ArrayList<LocaleItem> data, String selectedItemId) {
private CustomAdapter(ArrayList<LocaleItem> data, String selectedItemId)
{
this.dataSet = data;
this.selectedItemId = selectedItemId;
for (LocaleItem l : data) {
if (l.getCode().equals(selectedItemId)) {
for (LocaleItem l : data)
{
if (l.getCode().equals(selectedItemId))
{
l.setSelected(true);
}
}
}
@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
public void onBindViewHolder(CustomViewHolder holder, int position)
{
LocaleItem item = dataSet.get(position);
holder.name.setText(item.getName());
holder.itemLayout.setOnClickListener(v -> {
for (int i = 0; i < dataSet.size(); i++) {
holder.itemLayout.setOnClickListener(v ->
{
for (int i = 0; i < dataSet.size(); i++)
{
dataSet.get(i).setSelected(false);
}
dataSet.get(position).setSelected(true);
@ -129,11 +152,12 @@ public class SelectLocaleActivity extends BaseActivity {
notifyDataSetChanged();
});
holder.checkbox.setSelected(item.isSelected());
holder.radio.setChecked(item.isSelected());
}
@Override
public int getItemCount() {
public int getItemCount()
{
return dataSet.size();
}
}

@ -5,7 +5,6 @@ import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
@ -13,17 +12,19 @@ import androidx.recyclerview.widget.RecyclerView;
import com.alphawallet.app.R;
import com.alphawallet.app.ui.widget.divider.ListDivider;
import com.alphawallet.app.widget.StandardHeader;
import com.alphawallet.app.widget.TestNetDialog;
import com.google.android.material.switchmaterial.SwitchMaterial;
public abstract class SelectNetworkBaseActivity extends BaseActivity {
public abstract class SelectNetworkBaseActivity extends BaseActivity
{
RecyclerView mainnetRecyclerView;
RecyclerView testnetRecyclerView;
StandardHeader mainnetHeader;
StandardHeader testnetHeader;
SwitchMaterial mainnetSwitch;
SwitchMaterial testnetSwitch;
TestNetDialog testnetDialog;
FrameLayout mainnetFrame;
FrameLayout testnetFrame;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
@ -38,7 +39,8 @@ public abstract class SelectNetworkBaseActivity extends BaseActivity {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_add, menu);
return super.onCreateOptionsMenu(menu);
}
@ -72,11 +74,11 @@ public abstract class SelectNetworkBaseActivity extends BaseActivity {
private void initViews()
{
mainnetFrame = findViewById(R.id.mainnet_frame);
testnetFrame = findViewById(R.id.testnet_frame);
mainnetHeader = findViewById(R.id.mainnet_header);
testnetHeader = findViewById(R.id.testnet_header);
mainnetSwitch = findViewById(R.id.mainnet_switch);
testnetSwitch = findViewById(R.id.testnet_switch);
mainnetSwitch = mainnetHeader.getSwitch();
testnetSwitch = testnetHeader.getSwitch();
mainnetRecyclerView = findViewById(R.id.main_list);
testnetRecyclerView = findViewById(R.id.test_list);
@ -90,8 +92,8 @@ public abstract class SelectNetworkBaseActivity extends BaseActivity {
void hideSwitches()
{
testnetFrame.setVisibility(View.GONE);
mainnetFrame.setVisibility(View.GONE);
mainnetHeader.setVisibility(View.GONE);
testnetHeader.setVisibility(View.GONE);
}
void toggleListVisibility(boolean isMainNetActive)

@ -109,7 +109,6 @@ public class SelectNetworkFilterActivity extends SelectNetworkBaseActivity imple
LayoutInflater inflater = LayoutInflater.from(SelectNetworkFilterActivity.this);
View popupView = inflater.inflate(R.layout.popup_view_delete_network, null);
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, true);
@ -136,7 +135,6 @@ public class SelectNetworkFilterActivity extends SelectNetworkBaseActivity imple
popupView.measure(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
popupWindow.setHeight(popupView.getMeasuredHeight());
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
popupWindow.setElevation(5);
popupWindow.showAsDropDown(view);

@ -0,0 +1,79 @@
package com.alphawallet.app.ui;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import com.alphawallet.app.C;
import com.alphawallet.app.R;
import com.alphawallet.app.viewmodel.SelectThemeViewModel;
import dagger.hilt.android.AndroidEntryPoint;
@AndroidEntryPoint
public class SelectThemeActivity extends BaseActivity
{
private SelectThemeViewModel viewModel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_theme);
initViewModel();
initViews();
toolbar();
setTitle(getString(R.string.title_select_theme));
}
private void initViewModel()
{
viewModel = new ViewModelProvider(this).get(SelectThemeViewModel.class);
}
private void initViews()
{
LinearLayout lightThemeLayout = findViewById(R.id.layout_theme_light);
LinearLayout darkThemeLayout = findViewById(R.id.layout_theme_dark);
LinearLayout autoThemeLayout = findViewById(R.id.layout_theme_auto);
RadioGroup radioGroup = findViewById(R.id.radio_group);
lightThemeLayout.setOnClickListener(v -> radioGroup.check(R.id.radio_theme_light));
darkThemeLayout.setOnClickListener(v -> radioGroup.check(R.id.radio_theme_dark));
autoThemeLayout.setOnClickListener(v -> radioGroup.check(R.id.radio_theme_auto));
int theme = viewModel.getTheme();
if (theme == C.THEME_LIGHT)
{
radioGroup.check(R.id.radio_theme_light);
}
else if (theme == C.THEME_DARK)
{
radioGroup.check(R.id.radio_theme_dark);
}
else
{
radioGroup.check(R.id.radio_theme_auto);
}
radioGroup.setOnCheckedChangeListener((group, checkedId) ->
{
if (checkedId == R.id.radio_theme_light)
{
viewModel.setTheme(getApplicationContext(), C.THEME_LIGHT);
}
else if (checkedId == R.id.radio_theme_dark)
{
viewModel.setTheme(getApplicationContext(), C.THEME_DARK);
}
else
{
viewModel.setTheme(getApplicationContext(), C.THEME_AUTO);
}
finish();
});
}
}

@ -492,7 +492,6 @@ public class SellDetailActivity extends BaseActivity implements TokensAdapterCal
dialog.setSecondaryButtonText(R.string.dialog_cancel_back);
dialog.setPrimaryButtonListener(v1 -> sellLinkFinal(universalLink));
dialog.setSecondaryButtonListener(v1 -> dialog.dismiss());
dialog.showShareLink();
dialog.show();
}

@ -173,7 +173,7 @@ public class SendActivity extends BaseActivity implements AmountReadyCallback, S
{
onBack();
}
else if (item.getItemId() == R.id.action_qr)
else if (item.getItemId() == R.id.action_show_contract)
{
viewModel.showContractInfo(this, wallet, token);
}

@ -98,11 +98,7 @@ public class SetWatchWalletFragment extends ImportFragment implements AddressRea
{
try
{
importButton.setActivated(enabled);
importButton.setClickable(enabled);
int colorId = enabled ? R.color.nasty_green : R.color.inactive_green;
if (getContext() != null)
importButton.setBackgroundColor(getContext().getColor(colorId));
importButton.setEnabled(enabled);
}
catch (Exception e)
{

@ -140,8 +140,6 @@ public class TokenActivity extends BaseActivity implements PageReadyCallback, St
//TODO: Send event details
icon = findViewById(R.id.token_icon);
SystemView systemView = findViewById(R.id.system_view);
systemView.hide();
toolbar();
setTitle(getString(R.string.activity_label));
@ -301,14 +299,15 @@ public class TokenActivity extends BaseActivity implements PageReadyCallback, St
transaction.getDestination(token);
eventAction.setText(operationName);
eventActionSymbol.setText(sym);
eventAction.append(" " + sym);
//amount
String transactionValue = token.getTransactionResultValue(transaction, TRANSACTION_BALANCE_PRECISION);
if (!token.shouldShowSymbol(transaction) && transaction.input.length() >= FUNCTION_LENGTH)
{
eventAmount.setText(transaction.input.substring(0, FUNCTION_LENGTH));
eventActionSymbol.setText(getString(R.string.sent_to, token.getFullName()));
eventAction.setText(operationName + " " + getString(R.string.sent_to, token.getFullName()));
}
else if (TextUtils.isEmpty(transactionValue))
{

@ -36,9 +36,6 @@ import com.alphawallet.app.viewmodel.TokenAlertsViewModel;
import com.alphawallet.ethereum.EthereumNetworkBase;
import java.util.List;
import java.util.Objects;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;
@ -145,26 +142,22 @@ public class TokenAlertsFragment extends BaseFragment implements View.OnClickLis
if (getActivity() != null)
{
icon = ContextCompat.getDrawable(getActivity(), R.drawable.ic_close);
background = new ColorDrawable(ContextCompat.getColor(getActivity(), R.color.cancel_red));
if (icon != null)
{
icon.setTint(ContextCompat.getColor(getActivity(), R.color.error_inverse));
}
background = new ColorDrawable(ContextCompat.getColor(getActivity(), R.color.error));
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTypeface(ResourcesCompat.getFont(getContext(), R.font.font_semibold));
int textSize = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP,
17,
getActivity().getResources().getDisplayMetrics()
);
textPaint.setTextSize((int) getResources().getDimension(R.dimen.sp17));
textPaint.setColor(getResources().getColor(R.color.error_inverse, getContext().getTheme()));
swipeControlWidth = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
120,
getActivity().getResources().getDisplayMetrics()
);
textPaint.setTextSize(textSize);
textPaint.setColor(getResources().getColor(R.color.white, getContext().getTheme()));
}
}

@ -56,7 +56,6 @@ public class TokenDetailActivity extends BaseActivity implements StandardFunctio
private TokenFunctionViewModel viewModel;
private NFTImageView assetImage;
private TextView title;
private TextView name;
private TextView desc;
private TextView id;
@ -72,7 +71,6 @@ public class TokenDetailActivity extends BaseActivity implements StandardFunctio
private BigInteger tokenId;
private void initViews() {
title = findViewById(R.id.title);
assetImage = findViewById(R.id.layout_image);
name = findViewById(R.id.name);
desc = findViewById(R.id.description);

@ -108,8 +108,6 @@ public class TokenFunctionActivity extends BaseActivity implements StandardFunct
viewModel.gasEstimateComplete().observe(this, this::checkConfirm);
viewModel.transactionFinalised().observe(this, this::txWritten);
SystemView systemView = findViewById(R.id.system_view);
systemView.hide();
functionBar = findViewById(R.id.layoutButtons);
long chainId = getIntent().getLongExtra(C.EXTRA_CHAIN_ID, EthereumNetworkBase.MAINNET_ID);
initViews(viewModel.getTokenService().getToken(chainId, getIntent().getStringExtra(C.EXTRA_ADDRESS)));

@ -642,7 +642,6 @@ public class TransferTicketDetailActivity extends BaseActivity
confirmationDialog.setSecondaryButtonText(R.string.dialog_cancel_back);
confirmationDialog.setPrimaryButtonListener(v1 -> transferLinkFinal(universalLink));
confirmationDialog.setSecondaryButtonListener(v1 -> confirmationDialog.dismiss());
confirmationDialog.showShareLink();
confirmationDialog.show();
}

@ -199,8 +199,6 @@ public class WalletActionsActivity extends BaseActivity implements Runnable, Vie
findViewById(R.id.layout_backup_method).setVisibility(View.GONE);
}
walletSelectedIcon.setImageResource(R.drawable.ic_copy);
inputAddress.setAddress(wallet.ENSname);
inputAddress.setAddressCallback(this);
}

@ -616,12 +616,12 @@ public class WalletConnectActivity extends BaseActivity implements ActionSheetCa
if (client == null || !client.isConnected())
{
statusText.setText(R.string.not_connected);
statusText.setTextColor(getColor(R.color.cancel_red));
statusText.setTextColor(getColor(R.color.error));
}
else
{
statusText.setText(R.string.online);
statusText.setTextColor(getColor(R.color.nasty_green));
statusText.setTextColor(getColor(R.color.positive));
}
}));
}

@ -59,7 +59,6 @@ import com.alphawallet.app.ui.widget.TokensAdapterCallback;
import com.alphawallet.app.ui.widget.adapter.TokensAdapter;
import com.alphawallet.app.ui.widget.entity.AvatarWriteCallback;
import com.alphawallet.app.ui.widget.entity.WarningData;
import com.alphawallet.app.ui.widget.holder.ManageTokensHolder;
import com.alphawallet.app.ui.widget.holder.TokenGridHolder;
import com.alphawallet.app.ui.widget.holder.TokenHolder;
import com.alphawallet.app.ui.widget.holder.WarningHolder;
@ -77,8 +76,6 @@ import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
@ -126,9 +123,12 @@ public class WalletFragment extends BaseFragment implements
View view = inflater.inflate(R.layout.fragment_wallet, container, false);
LocaleUtils.setActiveLocale(getContext()); // Can't be placed before above line
if (CustomViewSettings.canAddTokens()) {
if (CustomViewSettings.canAddTokens())
{
toolbar(view, R.menu.menu_wallet, this::onMenuItemClick);
} else {
}
else
{
toolbar(view);
}
@ -149,9 +149,11 @@ public class WalletFragment extends BaseFragment implements
addressAvatar.setWaiting();
getChildFragmentManager()
.setFragmentResultListener(SEARCH_FRAGMENT, this, (requestKey, bundle) -> {
.setFragmentResultListener(SEARCH_FRAGMENT, this, (requestKey, bundle) ->
{
Fragment fragment = getChildFragmentManager().findFragmentByTag(SEARCH_FRAGMENT);
if (fragment != null && fragment.isVisible() && !fragment.isDetached()) {
if (fragment != null && fragment.isVisible() && !fragment.isDetached())
{
fragment.onDetach();
getChildFragmentManager().beginTransaction()
.remove(fragment)
@ -162,7 +164,8 @@ public class WalletFragment extends BaseFragment implements
return view;
}
private void initList() {
private void initList()
{
adapter = new TokensAdapter(this, viewModel.getAssetDefinitionService(), viewModel.getTokensService(),
tokenManagementLauncher);
adapter.setHasStableIds(true);
@ -179,7 +182,8 @@ public class WalletFragment extends BaseFragment implements
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
private void initViewModel() {
private void initViewModel()
{
viewModel = new ViewModelProvider(this)
.get(WalletViewModel.class);
viewModel.progress().observe(getViewLifecycleOwner(), systemView::showProgress);
@ -190,7 +194,8 @@ public class WalletFragment extends BaseFragment implements
viewModel.getTokensService().startWalletSync(this);
}
private void initViews(@NonNull View view) {
private void initViews(@NonNull View view)
{
refreshLayout = view.findViewById(R.id.refresh_layout);
systemView = view.findViewById(R.id.system_view);
recyclerView = view.findViewById(R.id.list);
@ -204,19 +209,21 @@ public class WalletFragment extends BaseFragment implements
largeTitleView = view.findViewById(R.id.large_title_view);
((ProgressView)view.findViewById(R.id.progress_view)).hide();
((ProgressView) view.findViewById(R.id.progress_view)).hide();
}
private void onDefaultWallet(Wallet wallet)
{
if (CustomViewSettings.showManageTokens()) {
if (CustomViewSettings.showManageTokens())
{
adapter.setWalletAddress(wallet.address);
}
addressAvatar.bind(wallet, this);
addressAvatar.setVisibility(View.VISIBLE);
addressAvatar.setOnClickListener(v -> {
addressAvatar.setOnClickListener(v ->
{
// open wallets activity
viewModel.showManageWallets(getContext(), false);
});
@ -242,14 +249,16 @@ public class WalletFragment extends BaseFragment implements
.like("address", ADDRESS_FORMAT)
.greaterThan("addedTime", (updateTime + 1))
.findAllAsync();
realmUpdates.addChangeListener(realmTokens -> {
realmUpdates.addChangeListener(realmTokens ->
{
long lastUpdateTime = updateTime;
List<TokenCardMeta> metas = new ArrayList<>();
//make list
for (RealmToken t : realmTokens)
{
if (t.getUpdateTime() > lastUpdateTime) lastUpdateTime = t.getUpdateTime();
if (!viewModel.getTokensService().getNetworkFilters().contains(t.getChainId())) continue;
if (!viewModel.getTokensService().getNetworkFilters().contains(t.getChainId()))
continue;
if (viewModel.isChainToken(t.getChainId(), t.getTokenAddress())) continue;
String balance = TokensRealmSource.convertStringBalance(t.getBalance(), t.getContractType());
@ -273,7 +282,8 @@ public class WalletFragment extends BaseFragment implements
private void updateMetas(List<TokenCardMeta> metas)
{
handler.post(() -> {
handler.post(() ->
{
if (metas.size() > 0)
{
adapter.setTokens(metas.toArray(new TokenCardMeta[0]));
@ -317,7 +327,7 @@ public class WalletFragment extends BaseFragment implements
largeTitleView.subtitle.setText(getString(R.string.wallet_total_change, TickerService.getCurrencyString(fiatValues.first - fiatValues.second),
TickerService.getPercentageConversion(changePercent)));
largeTitleView.title.setText(TickerService.getCurrencyString(fiatValues.first));
int color = ContextCompat.getColor(requireContext(), changePercent < 0 ? R.color.red : R.color.green);
int color = ContextCompat.getColor(requireContext(), changePercent < 0 ? R.color.negative : R.color.positive);
largeTitleView.subtitle.setTextColor(color);
if (viewModel.getWallet() != null && viewModel.getWallet().type != WalletType.WATCH && isVisible)
@ -333,7 +343,8 @@ public class WalletFragment extends BaseFragment implements
private void refreshList()
{
handler.post(() -> {
handler.post(() ->
{
adapter.clear();
viewModel.prepare();
viewModel.notifyRefresh();
@ -446,7 +457,8 @@ public class WalletFragment extends BaseFragment implements
}
@Override
public void onTokenClick(View view, Token token, List<BigInteger> ids, boolean selected) {
public void onTokenClick(View view, Token token, List<BigInteger> ids, boolean selected)
{
if (selectedToken == null)
{
getParentFragmentManager().setFragmentResult(C.TOKEN_CLICK, new Bundle());
@ -471,19 +483,21 @@ public class WalletFragment extends BaseFragment implements
}
@Override
public void onBuyToken() {
public void onBuyToken()
{
Intent intent = viewModel.getBuyIntent(getCurrentWallet().address);
((HomeActivity)getActivity()).onActivityResult(C.TOKEN_SEND_ACTIVITY, RESULT_OK, intent);
((HomeActivity) getActivity()).onActivityResult(C.TOKEN_SEND_ACTIVITY, RESULT_OK, intent);
}
@Override
public void onResume() {
public void onResume()
{
super.onResume();
currentTabPos = TokenFilter.ALL;
selectedToken = null;
if (viewModel == null)
{
((HomeActivity)getActivity()).resetFragment(WalletPage.WALLET);
((HomeActivity) getActivity()).resetFragment(WalletPage.WALLET);
}
else if (largeTitleView != null)
{
@ -522,7 +536,8 @@ public class WalletFragment extends BaseFragment implements
if (importFileName != null)
{
ContractLocator importToken = viewModel.getAssetDefinitionService().getHoldingContract(importFileName);
if (importToken != null) Toast.makeText(getContext(), importToken.address, Toast.LENGTH_LONG).show();
if (importToken != null)
Toast.makeText(getContext(), importToken.address, Toast.LENGTH_LONG).show();
if (importToken != null && adapter != null) adapter.setScrollToken(importToken);
importFileName = null;
}
@ -554,8 +569,7 @@ public class WalletFragment extends BaseFragment implements
wData.title = getString(R.string.time_to_backup_wallet);
wData.detail = getString(R.string.recommend_monthly_backup);
wData.buttonText = getString(R.string.back_up_wallet_action, viewModel.getWalletAddr().substring(0, 5));
wData.colour = R.color.slate_grey;
wData.buttonColour = R.color.backup_grey;
wData.colour = R.color.text_secondary;
wData.wallet = viewModel.getWallet();
adapter.addWarning(wData);
break;
@ -564,25 +578,30 @@ public class WalletFragment extends BaseFragment implements
wData.title = getString(R.string.wallet_not_backed_up);
wData.detail = getString(R.string.not_backed_up_detail);
wData.buttonText = getString(R.string.back_up_wallet_action, viewModel.getWalletAddr().substring(0, 5));
wData.colour = R.color.warning_red;
wData.buttonColour = R.color.warning_dark_red;
wData.colour = R.color.error;
wData.wallet = viewModel.getWallet();
adapter.addWarning(wData);
break;
}
}
private void onError(ErrorEnvelope errorEnvelope) {
if (errorEnvelope.code == EMPTY_COLLECTION) {
private void onError(ErrorEnvelope errorEnvelope)
{
if (errorEnvelope.code == EMPTY_COLLECTION)
{
systemView.showEmpty(getString(R.string.no_tokens));
} else {
}
else
{
systemView.showError(getString(R.string.error_fail_load_tokens), this);
}
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.try_again) {
public void onClick(View view)
{
if (view.getId() == R.id.try_again)
{
viewModel.prepare();
}
}
@ -607,7 +626,8 @@ public class WalletFragment extends BaseFragment implements
//reload tokens
viewModel.reloadTokens();
handler.post(() -> {
handler.post(() ->
{
//first abort the current operation
adapter.clear();
//show syncing
@ -619,15 +639,16 @@ public class WalletFragment extends BaseFragment implements
@Override
public void run()
{
if (selectedToken != null && selectedToken.findViewById(R.id.token_layout) != null)
{
selectedToken.findViewById(R.id.token_layout).setBackgroundResource(R.drawable.background_marketplace_event);
}
// if (selectedToken != null && selectedToken.findViewById(R.id.token_layout) != null)
// {
// selectedToken.findViewById(R.id.token_layout).setBackgroundResource(R.drawable.background_marketplace_event);
// }
selectedToken = null;
}
ActivityResultLauncher<Intent> handleBackupClick = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
result ->
{
String keyBackup = null;
boolean noLockScreen = false;
Intent data = result.getData();
@ -635,13 +656,13 @@ public class WalletFragment extends BaseFragment implements
if (data != null) noLockScreen = data.getBooleanExtra("nolock", false);
if (result.getResultCode() == RESULT_OK)
{
((HomeActivity)getActivity()).backupWalletSuccess(keyBackup);
((HomeActivity) getActivity()).backupWalletSuccess(keyBackup);
}
else
{
((HomeActivity)getActivity()).backupWalletFail(keyBackup, noLockScreen);
((HomeActivity) getActivity()).backupWalletFail(keyBackup, noLockScreen);
}
});
});
@Override
public void BackupClick(Wallet wallet)
@ -666,14 +687,16 @@ public class WalletFragment extends BaseFragment implements
@Override
public void remindMeLater(Wallet wallet)
{
handler.post(() -> {
handler.post(() ->
{
if (viewModel != null) viewModel.setKeyWarningDismissTime(wallet.address);
if (adapter != null) adapter.removeBackupWarning();
});
}
final ActivityResultLauncher<Intent> tokenManagementLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
result ->
{
if (result.getData() == null) return;
ArrayList<ContractLocator> tokenData = result.getData().getParcelableArrayListExtra(ADDED_TOKEN);
Bundle b = new Bundle();
@ -683,7 +706,8 @@ public class WalletFragment extends BaseFragment implements
public void storeWalletBackupTime(String backedUpKey)
{
handler.post(() -> {
handler.post(() ->
{
if (viewModel != null) viewModel.setKeyBackupTime(backedUpKey);
if (adapter != null) adapter.removeBackupWarning();
});
@ -701,30 +725,36 @@ public class WalletFragment extends BaseFragment implements
viewModel.saveAvatar(wallet);
}
public class SwipeCallback extends ItemTouchHelper.SimpleCallback {
public class SwipeCallback extends ItemTouchHelper.SimpleCallback
{
private final TokensAdapter mAdapter;
private Drawable icon;
private ColorDrawable background;
SwipeCallback(TokensAdapter adapter) {
SwipeCallback(TokensAdapter adapter)
{
super(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
mAdapter = adapter;
if (getActivity() != null) {
if (getActivity() != null)
{
icon = ContextCompat.getDrawable(getActivity(), R.drawable.ic_hide_token);
if (icon != null) {
icon.setTint(ContextCompat.getColor(getActivity(), R.color.white));
if (icon != null)
{
icon.setTint(ContextCompat.getColor(getActivity(), R.color.error_inverse));
}
background = new ColorDrawable(ContextCompat.getColor(getActivity(), R.color.cancel_red));
background = new ColorDrawable(ContextCompat.getColor(getActivity(), R.color.error));
}
}
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder viewHolder1) {
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder viewHolder1)
{
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i)
{
if (viewHolder instanceof WarningHolder)
{
remindMeLater(viewModel.getWallet());
@ -739,7 +769,8 @@ public class WalletFragment extends BaseFragment implements
{
Snackbar snackbar = Snackbar
.make(viewHolder.itemView, token.tokenInfo.name + " " + getContext().getString(R.string.token_hidden), Snackbar.LENGTH_LONG)
.setAction(getString(R.string.action_snackbar_undo), view -> {
.setAction(getString(R.string.action_snackbar_undo), view ->
{
viewModel.setTokenEnabled(token, true);
//adapter.updateToken(token.tokenInfo.chainId, token.getAddress(), true);
});
@ -750,10 +781,11 @@ public class WalletFragment extends BaseFragment implements
}
@Override
public int getSwipeDirs(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
public int getSwipeDirs(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder)
{
if (viewHolder.getItemViewType() == TokenHolder.VIEW_TYPE)
{
Token t = ((TokenHolder)viewHolder).token;
Token t = ((TokenHolder) viewHolder).token;
if (t != null && t.isEthereum()) return 0;
}
else
@ -765,7 +797,8 @@ public class WalletFragment extends BaseFragment implements
}
@Override
public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive)
{
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
View itemView = viewHolder.itemView;
@ -774,20 +807,25 @@ public class WalletFragment extends BaseFragment implements
int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
int iconBottom = iconTop + icon.getIntrinsicHeight();
if (dX > 0) {
if (dX > 0)
{
int iconLeft = itemView.getLeft() + iconMargin + icon.getIntrinsicWidth();
int iconRight = itemView.getLeft() + iconMargin;
icon.setBounds(iconRight, iconTop, iconLeft, iconBottom);
background.setBounds(itemView.getLeft(), itemView.getTop(),
itemView.getLeft() + ((int) dX) + offset,
itemView.getBottom());
} else if (dX < 0) {
}
else if (dX < 0)
{
int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth();
int iconRight = itemView.getRight() - iconMargin;
icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);
background.setBounds(itemView.getRight() + ((int) dX) - offset,
itemView.getTop(), itemView.getRight(), itemView.getBottom());
} else {
}
else
{
background.setBounds(0, 0, 0, 0);
}
@ -802,30 +840,38 @@ public class WalletFragment extends BaseFragment implements
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.action_my_wallet) {
public boolean onMenuItemClick(MenuItem menuItem)
{
if (menuItem.getItemId() == R.id.action_my_wallet)
{
viewModel.showMyAddress(getContext());
}
if (menuItem.getItemId() == R.id.action_scan) {
if (menuItem.getItemId() == R.id.action_scan)
{
viewModel.showQRCodeScanning(getActivity());
}
return super.onMenuItemClick(menuItem);
}
private void initNotificationView(View view) {
private void initNotificationView(View view)
{
NotificationView notificationView = view.findViewById(R.id.notification);
boolean hasShownWarning = viewModel.isMarshMallowWarningShown();
if (!hasShownWarning && android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
if (!hasShownWarning && android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.M)
{
notificationView.setNotificationBackgroundColor(R.color.indigo);
notificationView.setTitle(getContext().getString(R.string.title_version_support_warning));
notificationView.setMessage(getContext().getString(R.string.message_version_support_warning));
notificationView.setPrimaryButtonText(getContext().getString(R.string.hide_notification));
notificationView.setPrimaryButtonListener(() -> {
notificationView.setPrimaryButtonListener(() ->
{
notificationView.setVisibility(View.GONE);
viewModel.setMarshMallowWarning(true);
});
} else {
}
else
{
notificationView.setVisibility(View.GONE);
}
}

@ -41,8 +41,6 @@ import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.snackbar.Snackbar;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;
@AndroidEntryPoint
@ -299,7 +297,8 @@ public class WalletsActivity extends BaseActivity implements
addWalletView.setOnImportWalletClickListener(this);
addWalletView.setOnWatchWalletClickListener(this);
addWalletView.setOnCloseActionListener(this);
dialog = new BottomSheetDialog(this, R.style.FullscreenBottomSheetDialogStyle);
dialog = new BottomSheetDialog(this);
// dialog = new BottomSheetDialog(this, R.style.Aw_Component_BottomSheetDialog);
dialog.setContentView(addWalletView);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);

@ -124,7 +124,7 @@ public class ActivityAdapter extends RecyclerView.Adapter<BinderViewHolder<?>> i
return new EventHolder(parent, tokensService, fetchTransactionsInteract,
assetService, this);
case TransactionDateHolder.VIEW_TYPE:
return new TransactionDateHolder(R.layout.item_transactions_date_head, parent);
return new TransactionDateHolder(R.layout.item_standard_header, parent);
case LabelSortedItem.VIEW_TYPE:
return new LabelHolder(R.layout.item_activity_label, parent);
case TransferHolder.VIEW_TYPE:

@ -170,7 +170,7 @@ public class DappBrowserSuggestionsAdapter extends ArrayAdapter<DApp> implements
int end = lowerCaseText.length() + start;
SpannableStringBuilder builder = new SpannableStringBuilder(name);
if (start >= 0) {
int highlightColor = ContextCompat.getColor(getContext(), R.color.colorPrimaryDark);
int highlightColor = ContextCompat.getColor(getContext(), R.color.text_secondary);
builder.setSpan(new ForegroundColorSpan(highlightColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
//this.name.setText(builder);

@ -11,6 +11,7 @@ import androidx.recyclerview.widget.RecyclerView;
import com.alphawallet.app.R;
import com.alphawallet.app.ui.widget.entity.NetworkItem;
import com.google.android.material.checkbox.MaterialCheckBox;
import org.jetbrains.annotations.NotNull;
@ -72,14 +73,14 @@ public class MultiSelectNetworkAdapter extends RecyclerView.Adapter<MultiSelectN
holder.itemLayout.setOnClickListener(v -> clickListener(holder, position));
holder.manageView.setVisibility(View.VISIBLE);
holder.manageView.setOnClickListener(v -> editListener.onEditNetwork(networkList.get(position).getChainId(), holder.manageView));
holder.checkbox.setSelected(item.isSelected());
holder.checkbox.setChecked(item.isSelected());
}
}
private void clickListener(final MultiSelectNetworkAdapter.ViewHolder holder, final int position)
{
networkList.get(position).setSelected(!networkList.get(position).isSelected());
holder.checkbox.setSelected(networkList.get(position).isSelected());
holder.checkbox.setChecked(networkList.get(position).isSelected());
hasClicked = true;
}
@ -90,7 +91,7 @@ public class MultiSelectNetworkAdapter extends RecyclerView.Adapter<MultiSelectN
}
class ViewHolder extends RecyclerView.ViewHolder {
ImageView checkbox;
MaterialCheckBox checkbox;
TextView name;
View itemLayout;
View manageView;

@ -1,10 +1,11 @@
package com.alphawallet.app.ui.widget.adapter;
import static com.alphawallet.ethereum.EthereumNetworkBase.MAINNET_ID;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
@ -12,12 +13,12 @@ import androidx.recyclerview.widget.RecyclerView;
import com.alphawallet.app.R;
import com.alphawallet.app.ui.widget.entity.NetworkItem;
import com.google.android.material.radiobutton.MaterialRadioButton;
import java.util.ArrayList;
import static com.alphawallet.ethereum.EthereumNetworkBase.MAINNET_ID;
public class SingleSelectNetworkAdapter extends RecyclerView.Adapter<SingleSelectNetworkAdapter.ViewHolder> {
public class SingleSelectNetworkAdapter extends RecyclerView.Adapter<SingleSelectNetworkAdapter.ViewHolder>
{
private final ArrayList<NetworkItem> networkList;
private boolean hasSelection;
@ -69,7 +70,7 @@ public class SingleSelectNetworkAdapter extends RecyclerView.Adapter<SingleSelec
{
holder.name.setText(item.getName());
holder.itemLayout.setOnClickListener(v -> clickListener(holder, position));
holder.checkbox.setSelected(item.isSelected());
holder.radio.setChecked(item.isSelected());
}
}
@ -81,7 +82,7 @@ public class SingleSelectNetworkAdapter extends RecyclerView.Adapter<SingleSelec
}
networkList.get(position).setSelected(true);
notifyDataSetChanged();
holder.checkbox.setSelected(networkList.get(position).isSelected());
holder.radio.setChecked(networkList.get(position).isSelected());
}
@Override
@ -99,15 +100,16 @@ public class SingleSelectNetworkAdapter extends RecyclerView.Adapter<SingleSelec
}
}
class ViewHolder extends RecyclerView.ViewHolder {
ImageView checkbox;
class ViewHolder extends RecyclerView.ViewHolder
{
MaterialRadioButton radio;
TextView name;
View itemLayout;
ViewHolder(View view)
{
super(view);
checkbox = view.findViewById(R.id.checkbox);
radio = view.findViewById(R.id.radio);
name = view.findViewById(R.id.name);
itemLayout = view.findViewById(R.id.layout_list_item);
}

@ -9,6 +9,7 @@ import android.widget.TextView;
import com.alphawallet.app.R;
import com.alphawallet.app.ui.widget.OnSuggestionClickListener;
import com.google.android.material.button.MaterialButton;
import java.util.List;
@ -18,7 +19,7 @@ public class SuggestionsAdapter extends RecyclerView.Adapter<SuggestionsAdapter.
private final OnSuggestionClickListener onSuggestionClickListener;
class ViewHolder extends RecyclerView.ViewHolder {
TextView name;
MaterialButton name;
ViewHolder(@NonNull View itemView) {
super(itemView);
@ -57,7 +58,7 @@ public class SuggestionsAdapter extends RecyclerView.Adapter<SuggestionsAdapter.
String data = suggestionList.get(i);
viewHolder.name.setText(data);
viewHolder.itemView.setOnClickListener(v -> {
viewHolder.name.setOnClickListener(v -> {
String outputWord = data.replaceFirst(suggestion, "");
onSuggestionClickListener.onSuggestionClick(outputWord);
});

@ -1,188 +0,0 @@
package com.alphawallet.app.ui.widget.adapter;
import android.content.Context;
import android.os.Bundle;
import androidx.recyclerview.widget.RecyclerView;
import android.view.ViewGroup;
import com.alphawallet.app.R;
import com.alphawallet.app.entity.Wallet;
import com.alphawallet.app.entity.WalletType;
import com.alphawallet.app.interact.GenericWalletInteract;
import com.alphawallet.app.ui.widget.entity.WalletClickCallback;
import com.alphawallet.app.ui.widget.holder.BinderViewHolder;
import com.alphawallet.app.ui.widget.holder.TextHolder;
import com.alphawallet.app.ui.widget.holder.WalletHolder;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import io.realm.Realm;
public class WalletsAdapter extends RecyclerView.Adapter<BinderViewHolder> implements WalletClickCallback
{
private final OnSetWalletDefaultListener onSetWalletDefaultListener;
private final ArrayList<Wallet> wallets;
private Wallet defaultWallet = null;
private final Context context;
private final Realm realm;
private final GenericWalletInteract walletInteract;
public WalletsAdapter(Context ctx,
OnSetWalletDefaultListener onSetWalletDefaultListener, GenericWalletInteract genericWalletInteract) {
this.onSetWalletDefaultListener = onSetWalletDefaultListener;
this.wallets = new ArrayList<>();
this.context = ctx;
this.realm = genericWalletInteract.getWalletRealm();
this.walletInteract = genericWalletInteract;
}
@NotNull
@Override
public BinderViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
BinderViewHolder binderViewHolder = null;
switch (viewType) {
case WalletHolder.VIEW_TYPE:
binderViewHolder = new WalletHolder(R.layout.item_wallet_manage, parent, this, realm);
break;
case TextHolder.VIEW_TYPE:
binderViewHolder = new TextHolder(R.layout.item_text_view, parent);
break;
default:
break;
}
return binderViewHolder;
}
@Override
public void onBindViewHolder(@NotNull BinderViewHolder holder, int position) {
switch (getItemViewType(position)) {
case WalletHolder.VIEW_TYPE:
Wallet wallet = wallets.get(position);
Bundle bundle = new Bundle();
bundle.putBoolean(
WalletHolder.IS_DEFAULT_ADDITION,
defaultWallet != null && defaultWallet.sameAddress(wallet.address));
bundle.putBoolean(WalletHolder.IS_LAST_ITEM, getItemCount() == 1);
holder.bind(wallet, bundle);
break;
case TextHolder.VIEW_TYPE:
wallet = wallets.get(position);
holder.bind(wallet.address);
break;
default:
break;
}
}
@Override
public int getItemCount() {
return wallets.size();
}
@Override
public int getItemViewType(int position) {
switch (wallets.get(position).type)
{
default:
case WATCH:
case KEYSTORE:
case KEYSTORE_LEGACY:
case HDKEY:
return WalletHolder.VIEW_TYPE;
case TEXT_MARKER:
return TextHolder.VIEW_TYPE;
}
}
public void setDefaultWallet(Wallet wallet) {
this.defaultWallet = wallet;
notifyDataSetChanged();
}
public void setWallets(Wallet[] wallets)
{
this.wallets.clear();
boolean hasLegacyWallet = false;
boolean hasWatchWallet = false;
if (wallets != null)
{
Wallet yourWallets = new Wallet(context.getString(R.string.your_wallets));
yourWallets.type = WalletType.TEXT_MARKER;
this.wallets.add(yourWallets);
//Add HD Wallets
for (Wallet w : wallets)
{
switch (w.type)
{
case KEYSTORE_LEGACY:
case KEYSTORE:
hasLegacyWallet = true;
break;
case HDKEY:
this.wallets.add(w);
break;
case WATCH:
hasWatchWallet = true;
break;
default:
break;
}
}
if (hasLegacyWallet)
{
Wallet legacyText = new Wallet(context.getString(R.string.legacy_wallets));
legacyText.type = WalletType.TEXT_MARKER;
this.wallets.add(legacyText);
for (Wallet w : wallets)
{
if (w.type == WalletType.KEYSTORE || w.type == WalletType.KEYSTORE_LEGACY)
{
this.wallets.add(w);
}
}
}
if (hasWatchWallet)
{
Wallet watchText = new Wallet(context.getString(R.string.watch_wallet));
watchText.type = WalletType.TEXT_MARKER;
this.wallets.add(watchText);
for (Wallet w : wallets)
{
if (w.type == WalletType.WATCH)
{
this.wallets.add(w);
}
}
}
}
notifyDataSetChanged();
}
@Override
public void onWalletClicked(Wallet wallet)
{
onSetWalletDefaultListener.onSetDefault(wallet);
}
@Override
public void ensAvatar(Wallet wallet)
{
walletInteract.updateWalletInfo(wallet, wallet.name, () -> { });
}
public void onDestroy()
{
realm.close();
}
public interface OnSetWalletDefaultListener {
void onSetDefault(Wallet wallet);
}
}

@ -58,7 +58,7 @@ public class WalletsSummaryAdapter extends RecyclerView.Adapter<BinderViewHolder
binderViewHolder = new WalletSummaryHolder(R.layout.item_wallet_summary_manage, parent, this, realm);
break;
case TextHolder.VIEW_TYPE:
binderViewHolder = new TextHolder(R.layout.item_text_view, parent);
binderViewHolder = new TextHolder(R.layout.item_standard_header, parent);
break;
case WalletSummaryHeaderHolder.VIEW_TYPE:
binderViewHolder = new WalletSummaryHeaderHolder(R.layout.item_wallet_summary_large_title, parent,this, realm);

@ -18,6 +18,8 @@ import androidx.annotation.Nullable;
import com.alphawallet.app.R;
import com.alphawallet.app.entity.tokens.Token;
import com.alphawallet.app.service.TickerService;
import com.alphawallet.app.util.Utils;
import com.google.android.material.color.MaterialColors;
import org.json.JSONArray;
import org.json.JSONObject;
@ -45,7 +47,8 @@ public class HistoryChart extends View
.retryOnConnectionFailure(false)
.build();
public enum Range {
public enum Range
{
Day(1),
Week(7),
@ -55,23 +58,28 @@ public class HistoryChart extends View
private final int value;
Range(int value) {
Range(int value)
{
this.value = value;
}
public int getValue() {
public int getValue()
{
return value;
}
}
// store tokens mapping and chart data
static class Cache {
static class Cache
{
Range range;
Map<Range, Datasource> datasourceMap = new HashMap<>();
Datasource getCurrentDatasource(Range range) {
if (datasourceMap.containsKey(range)) {
Datasource getCurrentDatasource(Range range)
{
if (datasourceMap.containsKey(range))
{
return datasourceMap.get(range);
}
return null;
@ -93,7 +101,8 @@ public class HistoryChart extends View
static Single<Datasource> fetchHistory(Range range, String tokenId)
{
return Single.fromCallable(() -> {
return Single.fromCallable(() ->
{
ArrayList<Pair<Long, Float>> entries = new ArrayList<>();
try
{
@ -103,7 +112,8 @@ public class HistoryChart extends View
.build();
okhttp3.Response response = httpClient.newCall(request)
.execute();
if (response.code() / 200 == 1) {
if (response.code() / 200 == 1)
{
JSONArray prices = new JSONObject(response.body().string()).getJSONArray("prices");
float minValue = Float.MAX_VALUE;
float maxValue = 0;
@ -128,7 +138,9 @@ public class HistoryChart extends View
ds.maxValue = maxValue;
return ds;
}
} catch (Exception e) {
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
@ -171,41 +183,28 @@ public class HistoryChart extends View
private void init()
{
paint.setColor(getResources().getColor(R.color.green, getContext().getTheme()));
paint.setColor(getResources().getColor(R.color.positive, getContext().getTheme()));
Resources r = getResources();
int strokeWidth = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
3,
2,
r.getDisplayMetrics()
);
paint.setStrokeWidth(strokeWidth);
paint.setDither(true);
greyPaint.setColor(getResources().getColor(R.color.black_12,getContext().getTheme()));
greyPaint.setColor(Utils.getColorFromAttr(getContext(), R.attr.colorSurfaceDark));
greyPaint.setStrokeWidth(1);
noDataTextPaint.setTextAlign(Paint.Align.CENTER);
int textSize = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP,
14,
r.getDisplayMetrics()
);
noDataTextPaint.setTextSize(textSize);
noDataTextPaint.setColor(getResources().getColor(R.color.black_12, getContext().getTheme()));
noDataTextPaint.setTextSize((int) getResources().getDimension(R.dimen.sp14));
noDataTextPaint.setColor(getResources().getColor(R.color.text_primary, getContext().getTheme()));
edgeValPaint.setTextAlign(Paint.Align.RIGHT);
edgeValPaint.setTextSize(
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP,
12,
r.getDisplayMetrics()
)
);
edgeValPaint.setColor(getResources().getColor(R.color.black, getContext().getTheme()));
edgeValPaint.setTextSize((int) getResources().getDimension(R.dimen.sp12));
edgeValPaint.setColor(getResources().getColor(R.color.text_primary, getContext().getTheme()));
}
public HistoryChart(Context context, @Nullable AttributeSet attrs)
@ -229,29 +228,28 @@ public class HistoryChart extends View
return;
}
// draw chart
float width = getWidth();
float height = getHeight();
//colour changes depending on first and last values
path.reset();
int color = datasource.isGreen() ? R.color.green : R.color.danger;
paint.setColor(getResources().getColor(color,getContext().getTheme()));
int color = datasource.isGreen() ? R.color.positive : R.color.negative;
paint.setColor(getResources().getColor(color, getContext().getTheme()));
float xScale = width / (datasource.maxTime() - datasource.minTime());
float yScale = ((height * 0.9f) / (datasource.maxValue() - datasource.minValue()));
for (float i = datasource.minValue();
i <= datasource.maxValue();
i = i + (datasource.maxValue() - datasource.minValue())/4) {
i = i + (datasource.maxValue() - datasource.minValue()) / 4)
{
float lineVal = height - (i - datasource.minValue()) * yScale;
greyLines.moveTo(0, lineVal);
greyLines.lineTo(width, lineVal);
}
greyPaint.setStyle(Paint.Style.STROKE);
canvas.drawPath(greyLines,greyPaint);
canvas.drawPath(greyLines, greyPaint);
for (int i = 0; i < datasource.entries.size(); i++)
{
@ -263,7 +261,8 @@ public class HistoryChart extends View
if (i == 0)
{
path.moveTo(x, y);
} else
}
else
{
path.lineTo(x, y);
}
@ -274,20 +273,24 @@ public class HistoryChart extends View
canvas.drawPath(path, paint);
// add min/max values to chart
canvas.drawText(String.format("%.02f", datasource.minValue()),width - TEXT_MARGIN,height,edgeValPaint);
canvas.drawText(String.format("%.02f",datasource.maxValue()),width - TEXT_MARGIN,0.05f*height,edgeValPaint);
canvas.drawText(String.format("%.02f", datasource.minValue()), width - TEXT_MARGIN, height, edgeValPaint);
canvas.drawText(String.format("%.02f", datasource.maxValue()), width - TEXT_MARGIN, 0.05f * height, edgeValPaint);
}
public void fetchHistory(Token token, final Range range)
{
// use cache
cache.range = range;
if (cache.getCurrentDatasource(range) != null) {
if (cache.getCurrentDatasource(range) != null)
{
invalidate();
return;
}
if (!TickerService.validateCoinGeckoAPI(token)) { return; } //wouldn't have tickers
if (!TickerService.validateCoinGeckoAPI(token))
{
return;
} //wouldn't have tickers
String coingeckoTokenId = token.isEthereum() ? chainPairs.get(token.tokenInfo.chainId)
: coinGeckoChainIdToAPIName.get(token.tokenInfo.chainId) + "/contract/" + token.getAddress().toLowerCase();
@ -301,7 +304,6 @@ public class HistoryChart extends View
}
}
private void onEntries(Range range, Datasource datasource)
{
// invalidate
@ -309,7 +311,8 @@ public class HistoryChart extends View
invalidate();
}
private void onError(Throwable throwable) {
private void onError(Throwable throwable)
{
throwable.printStackTrace();
}
}

@ -76,7 +76,7 @@ public class NumericInput extends AppCompatAutoCompleteTextView implements TextW
final Matcher addressMatch = numberFormatMatcher.matcher(s.toString());
if (!addressMatch.find())
{
setTextColor(getResources().getColor(R.color.warning_red));
setTextColor(getResources().getColor(R.color.error));
}
else
{

@ -23,6 +23,7 @@ import com.alphawallet.app.util.Utils;
import com.alphawallet.app.web3.Web3TokenView;
import com.alphawallet.app.web3.entity.PageReadyCallback;
import com.alphawallet.token.entity.TicketRange;
import com.google.android.material.radiobutton.MaterialRadioButton;
/**
* Created by James on 26/03/2019.
@ -38,7 +39,7 @@ public class AssetInstanceScriptHolder extends BinderViewHolder<TicketRange> imp
private final LinearLayout webWrapper;
private final boolean iconified;
private TokensAdapterCallback tokenClickListener;
private final AppCompatRadioButton itemSelect;
private final MaterialRadioButton itemSelect;
private final AssetDefinitionService assetDefinitionService; //need to cache this locally, unless we cache every string we need in the constructor
private boolean activeClick;
private final Handler handler = new Handler();

@ -4,7 +4,6 @@ import static com.alphawallet.ethereum.EthereumNetworkBase.MAINNET_ID;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
@ -12,14 +11,16 @@ import androidx.annotation.Nullable;
import com.alphawallet.app.R;
import com.alphawallet.app.entity.NetworkInfo;
import com.alphawallet.app.repository.EthereumNetworkBase;
import com.alphawallet.app.widget.StandardHeader;
/**
* Created by JB on 10/01/2022.
*/
public class ChainNameHeaderHolder extends BinderViewHolder<Long> {
public class ChainNameHeaderHolder extends BinderViewHolder<Long>
{
public static final int VIEW_TYPE = 2023; //TODO: Move these into an enum
private final TextView chainName;
private final StandardHeader chainName;
@Override
public void bind(@Nullable Long chainId, @NonNull Bundle addition)
@ -29,8 +30,9 @@ public class ChainNameHeaderHolder extends BinderViewHolder<Long> {
chainName.setText(info.name);
}
public ChainNameHeaderHolder(int res_id, ViewGroup parent) {
public ChainNameHeaderHolder(int res_id, ViewGroup parent)
{
super(res_id, parent);
chainName = findViewById(R.id.chain_name);
chainName = findViewById(R.id.header_chain_name);
}
}

@ -53,8 +53,6 @@ public class EventHolder extends BinderViewHolder<EventMeta> implements View.OnC
private final TextView type;
private final TextView address;
private final TextView value;
private final TextView supplemental;
private final LinearLayout transactionBackground;
private final AssetDefinitionService assetDefinition;
private final AdapterCallback refreshSignaller;
@ -75,15 +73,11 @@ public class EventHolder extends BinderViewHolder<EventMeta> implements View.OnC
address = findViewById(R.id.address);
type = findViewById(R.id.type);
value = findViewById(R.id.value);
supplemental = findViewById(R.id.supplimental);
transactionBackground = findViewById(R.id.layout_background);
tokensService = service;
itemView.setOnClickListener(this);
assetDefinition = svs;
fetchTransactionsInteract = interact;
refreshSignaller = signaller;
transactionBackground.setBackgroundResource(R.color.white);
}
@Override

@ -27,7 +27,6 @@ public class NFTAssetHolder extends BinderViewHolder<Pair<BigInteger, NFTAsset>>
final TextView title;
final TextView assetCategory;
final TextView assetCount;
final TextView selectionAmount;
final TextView tokenId;
public NFTAssetHolder(ViewGroup parent)
@ -38,7 +37,6 @@ public class NFTAssetHolder extends BinderViewHolder<Pair<BigInteger, NFTAsset>>
title = findViewById(R.id.title);
assetCategory = findViewById(R.id.subtitle);
assetCount = findViewById(R.id.count);
selectionAmount = findViewById(R.id.text_count);
tokenId = findViewById(R.id.token_id);
}

@ -3,6 +3,8 @@ package com.alphawallet.app.ui.widget.holder;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.alphawallet.app.R;
@ -16,16 +18,22 @@ public class TextHolder extends BinderViewHolder<String>
public static final int VIEW_TYPE = 1041;
private final TextView text;
private final View separator;
public TextHolder(int resId, ViewGroup parent)
{
super(resId, parent);
text = findViewById(R.id.text);
text = findViewById(R.id.text_header);
separator = findViewById(R.id.separator);
}
@Override
public void bind(@Nullable String data, @NonNull Bundle addition)
{
if (data != null && data.length() > 0) text.setText(data);
if (data != null && data.length() > 0)
{
text.setText(data);
separator.setVisibility(View.GONE);
}
}
}

@ -15,6 +15,7 @@ import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
@ -55,14 +56,13 @@ public class TokenHolder extends BinderViewHolder<TokenCardMeta> implements View
private final View root24Hours;
private final ImageView image24h;
private final TextView textAppreciation;
private final View contractSeparator;
private final View layoutAppreciation;
private final LinearLayout extendedInfo;
private final AssetDefinitionService assetDefinition; //need to cache this locally, unless we cache every string we need in the constructor
private final TokensService tokensService;
private final TextView pendingText;
private final RelativeLayout tokenLayout;
private final MaterialCheckBox selectToken;
private final ProgressBar tickerProgress;
public Token token;
private TokensAdapterCallback tokensAdapterCallback;
@ -79,12 +79,12 @@ public class TokenHolder extends BinderViewHolder<TokenCardMeta> implements View
root24Hours = findViewById(R.id.root_24_hrs);
image24h = findViewById(R.id.image_24_hrs);
textAppreciation = findViewById(R.id.text_appreciation);
contractSeparator = findViewById(R.id.contract_seperator);
pendingText = findViewById(R.id.balance_eth_pending);
tokenLayout = findViewById(R.id.token_layout);
extendedInfo = findViewById(R.id.layout_extended_info);
layoutAppreciation = findViewById(R.id.layout_appreciation);
selectToken = findViewById(R.id.select_token);
tickerProgress = findViewById(R.id.ticker_progress);
itemView.setOnClickListener(this);
assetDefinition = assetService;
tokensService = tSvs;
@ -94,7 +94,6 @@ public class TokenHolder extends BinderViewHolder<TokenCardMeta> implements View
public void bind(@Nullable TokenCardMeta data, @NonNull Bundle addition)
{
layoutAppreciation.setForeground(null);
balanceCurrency.setTextColor(ContextCompat.getColor(getContext(), R.color.black));
if (data == null) { fillEmpty(); return; }
try
{
@ -112,9 +111,8 @@ public class TokenHolder extends BinderViewHolder<TokenCardMeta> implements View
}
tokenLayout.setVisibility(View.VISIBLE);
tokenLayout.setBackgroundResource(R.drawable.background_marketplace_event);
// tokenLayout.setBackgroundResource(R.drawable.background_marketplace_event);
if (EthereumNetworkRepository.isPriorityToken(token)) extendedInfo.setVisibility(View.GONE);
contractSeparator.setVisibility(View.GONE);
if (!TextUtils.isEmpty(data.getFilterText()) && data.getFilterText().equals(CHECK_MARK))
{
setupCheckButton(data);
@ -142,8 +140,6 @@ public class TokenHolder extends BinderViewHolder<TokenCardMeta> implements View
populateTicker();
setPendingAmount();
} catch (Exception ex) {
fillEmpty();
}
@ -155,20 +151,6 @@ public class TokenHolder extends BinderViewHolder<TokenCardMeta> implements View
}
private void setPendingAmount()
{
String pendingDiff = token.getPendingDiff();
if (pendingDiff != null)
{
pendingText.setText(pendingDiff);
pendingText.setTextColor(ContextCompat.getColor(getContext(), (pendingDiff.startsWith("-")) ? R.color.red : R.color.green));
}
else
{
pendingText.setText("");
}
}
private void populateTicker()
{
resetTickerViews();
@ -197,7 +179,6 @@ public class TokenHolder extends BinderViewHolder<TokenCardMeta> implements View
{
if (ticker != null)
{
hideIssuerViews();
layoutAppreciation.setVisibility(View.VISIBLE);
balanceCurrency.setVisibility(View.VISIBLE);
setTickerInfo(ticker);
@ -215,13 +196,17 @@ public class TokenHolder extends BinderViewHolder<TokenCardMeta> implements View
{
if ((System.currentTimeMillis() - ticker.updateTime) > TICKER_PERIOD_VALIDITY)
{
layoutAppreciation.setForeground(AppCompatResources.getDrawable(getContext(), R.color.translucentWhiteSolid));
balanceCurrency.setTextColor(ContextCompat.getColor(getContext(), R.color.dove_hint));
root24Hours.setVisibility(View.GONE);
textAppreciation.setVisibility(View.GONE);
tickerProgress.setVisibility(View.VISIBLE);
balanceCurrency.setAlpha(0.3f);
}
else
{
layoutAppreciation.setForeground(null);
balanceCurrency.setTextColor(ContextCompat.getColor(getContext(), R.color.black));
tickerProgress.setVisibility(View.GONE);
root24Hours.setVisibility(View.VISIBLE);
textAppreciation.setVisibility(View.VISIBLE);
balanceCurrency.setAlpha(1.0f);
}
}
@ -259,10 +244,6 @@ public class TokenHolder extends BinderViewHolder<TokenCardMeta> implements View
this.tokensAdapterCallback = tokensAdapterCallback;
}
private void hideIssuerViews() {
contractSeparator.setVisibility(View.GONE);
}
private void setTickerInfo(TokenTicker ticker)
{
//Set the fiat equivalent (leftmost value)
@ -290,7 +271,7 @@ public class TokenHolder extends BinderViewHolder<TokenCardMeta> implements View
double percentage = 0;
try {
percentage = Double.parseDouble(ticker.percentChange24h);
color = ContextCompat.getColor(getContext(), percentage < 0 ? R.color.red : R.color.green);
color = ContextCompat.getColor(getContext(), percentage < 0 ? R.color.negative : R.color.positive);
formattedPercents = ticker.percentChange24h.replace("-", "") + "%";
root24Hours.setBackgroundResource(percentage < 0 ? R.drawable.background_24h_change_red : R.drawable.background_24h_change_green);
text24Hours.setText(formattedPercents);

@ -4,6 +4,8 @@ import android.os.Bundle;
import android.text.format.DateUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
@ -16,11 +18,12 @@ public class TransactionDateHolder extends BinderViewHolder<Date> {
public static final int VIEW_TYPE = 1004;
private final TextView title;
private final View separator;
public TransactionDateHolder(int resId, ViewGroup parent) {
super(resId, parent);
title = findViewById(R.id.title);
title = findViewById(R.id.text_header);
separator = findViewById(R.id.separator);
}
@Override
@ -30,6 +33,7 @@ public class TransactionDateHolder extends BinderViewHolder<Date> {
} else {
title.setText(getDate(data));
}
separator.setVisibility(View.GONE);
}
private String getDate(Date date)

@ -155,7 +155,7 @@ public class TransactionHolder extends BinderViewHolder<TransactionMeta> impleme
layoutParams.setMarginStart(10);
String failure = getString(R.string.failed) + " ☹";
supplemental.setText(failure);
supplemental.setTextColor(ContextCompat.getColor(getContext(), R.color.red));
supplemental.setTextColor(ContextCompat.getColor(getContext(), R.color.error));
}
private void setTransactionStatus(String blockNumber, String error, boolean isPending)
@ -177,11 +177,6 @@ public class TransactionHolder extends BinderViewHolder<TransactionMeta> impleme
{
tokenIcon.setStatusIcon(StatusType.PENDING);
type.setText(R.string.pending_transaction);
transactionBackground.setBackgroundResource(R.drawable.background_pending_transaction);
}
else if (transactionBackground != null)
{
transactionBackground.setBackgroundResource(R.color.white);
}
}
}

@ -73,7 +73,6 @@ public class TransferHolder extends BinderViewHolder<TokenTransferData> implemen
fetchTransactionsInteract = interact;
findViewById(R.id.layout_background).setBackgroundResource(R.color.white);
}
@Override

@ -50,8 +50,6 @@ public class WalletHolder extends BinderViewHolder<Wallet> implements View.OnCli
private final TextView walletAddressText;
private final TextView wallet24hChange;
private final ImageView walletSelectedIcon;
private final int greyColor;
private final int blackColor;
private final Realm realm;
private RealmResults<RealmWalletData> realmUpdate;
@ -72,8 +70,6 @@ public class WalletHolder extends BinderViewHolder<Wallet> implements View.OnCli
wallet24hChange = findViewById(R.id.wallet_24h_change);
clickCallback = callback;
manageWalletLayout = findViewById(R.id.layout_manage_wallet);
greyColor = parent.getContext().getColor(R.color.greyffive);
blackColor = parent.getContext().getColor(R.color.text_black);
this.realm = realm;
}
@ -108,11 +104,6 @@ public class WalletHolder extends BinderViewHolder<Wallet> implements View.OnCli
if (!TextUtils.isEmpty(walletBalance) && walletBalance.startsWith("*"))
{
walletBalance = walletBalance.substring(1);
walletBalanceText.setTextColor(greyColor);
}
else
{
walletBalanceText.setTextColor(blackColor);
}
walletBalanceText.setText(walletBalance);
walletBalanceCurrency.setText(wallet.balanceSymbol);
@ -151,7 +142,7 @@ public class WalletHolder extends BinderViewHolder<Wallet> implements View.OnCli
{
//This sets the 24hr percentage change (rightmost value)
try {
int color = ContextCompat.getColor(getContext(), percentChange24h < 0 ? R.color.red : R.color.green);
int color = ContextCompat.getColor(getContext(), percentChange24h < 0 ? R.color.negative : R.color.positive);
BigDecimal percentChangeBI = BigDecimal.valueOf(percentChange24h).setScale(3, RoundingMode.DOWN);
String formattedPercents = (percentChange24h < 0 ? "-" : "+") + percentChangeBI + "%";
//wallet24hChange.setBackgroundResource(percentage < 0 ? R.drawable.background_24h_change_red : R.drawable.background_24h_change_green);
@ -170,7 +161,6 @@ public class WalletHolder extends BinderViewHolder<Wallet> implements View.OnCli
//update balance
if (realmWallets.size() == 0) return;
RealmWalletData realmWallet = realmWallets.first();
walletBalanceText.setTextColor(blackColor);
walletBalanceText.setText(realmWallet.getBalance());
String ensName = realmWallet.getENSName();
String name = realmWallet.getName();

@ -75,7 +75,7 @@ public class WalletSummaryHeaderHolder extends BinderViewHolder<Wallet> implemen
double change24h = fiatValue - oldFiatValue;
double percentChange24h = fiatValue != 0 ? (change24h/oldFiatValue)*100.0 : 0.0;
summaryChange.setVisibility(View.VISIBLE);
int color = ContextCompat.getColor(getContext(), percentChange24h < 0 ? R.color.red : R.color.green);
int color = ContextCompat.getColor(getContext(), percentChange24h < 0 ? R.color.negative : R.color.positive);
BigDecimal percentChangeBI = BigDecimal.valueOf(percentChange24h).setScale(3, RoundingMode.DOWN);
String changeTxt = TickerService.getCurrencyString(change24h);
String formattedPercents = (percentChange24h < 0 ? "" : "+") + percentChangeBI + "%";

@ -47,10 +47,7 @@ public class WalletSummaryHolder extends BinderViewHolder<Wallet> implements Vie
private final TextView walletNameText;
private final TextView walletAddressSeparator;
private final TextView walletAddressText;
private final ImageView walletSelectedIcon;
private final TextView wallet24hChange;
private final int greyColor;
private final int blackColor;
private final Realm realm;
private RealmResults<RealmWalletData> realmUpdate;
@ -66,13 +63,10 @@ public class WalletSummaryHolder extends BinderViewHolder<Wallet> implements Vie
walletNameText = findViewById(R.id.wallet_name);
walletAddressSeparator = findViewById(R.id.wallet_address_separator);
walletAddressText = findViewById(R.id.wallet_address);
walletSelectedIcon = findViewById(R.id.selected_wallet_indicator);
walletClickLayout = findViewById(R.id.wallet_click_layer);
wallet24hChange = findViewById(R.id.wallet_24h_change);
clickCallback = callback;
manageWalletLayout = findViewById(R.id.layout_manage_wallet);
greyColor = parent.getContext().getColor(R.color.greyffive);
blackColor = parent.getContext().getColor(R.color.text_black);
this.realm = realm;
}
@ -107,19 +101,12 @@ public class WalletSummaryHolder extends BinderViewHolder<Wallet> implements Vie
if (!TextUtils.isEmpty(walletBalance) && walletBalance.startsWith("*"))
{
walletBalance = walletBalance.substring(1);
walletBalanceText.setTextColor(greyColor);
}
else
{
walletBalanceText.setTextColor(blackColor);
}
walletBalanceText.setText(walletBalance);
walletBalanceCurrency.setText(wallet.balanceSymbol);
walletAddressText.setText(Utils.formatAddress(wallet.address));
walletSelectedIcon.setSelected(addition.getBoolean(IS_DEFAULT_ADDITION, false));
if (addition.getBoolean(IS_SYNCED, false))
{
walletIcon.finishWaiting();
@ -154,7 +141,7 @@ public class WalletSummaryHolder extends BinderViewHolder<Wallet> implements Vie
//This sets the 24hr percentage change (rightmost value)
try {
wallet24hChange.setVisibility(View.VISIBLE);
int color = ContextCompat.getColor(getContext(), percentChange24h < 0 ? R.color.red : R.color.green);
int color = ContextCompat.getColor(getContext(), percentChange24h < 0 ? R.color.negative : R.color.positive);
BigDecimal percentChangeBI = BigDecimal.valueOf(percentChange24h).setScale(3, RoundingMode.DOWN);
String formattedPercents = (percentChange24h < 0 ? "" : "+") + percentChangeBI + "%";
//wallet24hChange.setBackgroundResource(percentage < 0 ? R.drawable.background_24h_change_red : R.drawable.background_24h_change_green);

@ -1,9 +1,6 @@
package com.alphawallet.app.ui.widget.holder;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@ -13,8 +10,13 @@ import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import com.alphawallet.app.R;
import com.alphawallet.app.ui.widget.entity.WarningData;
import com.google.android.material.card.MaterialCardView;
/**
* Created by James on 18/07/2019.
@ -26,7 +28,7 @@ public class WarningHolder extends BinderViewHolder<WarningData>
public static final int VIEW_TYPE = 1015;
private final TextView title;
private final TextView detail;
private final LinearLayout layoutBackground;
private final MaterialCardView layoutBackground;
private final ImageView menuButton;
private final Button backupButton;
private final View popupAnchor;
@ -36,21 +38,28 @@ public class WarningHolder extends BinderViewHolder<WarningData>
{
title.setText(data.title);
detail.setText(data.detail);
layoutBackground.setBackgroundTintList(ContextCompat.getColorStateList(getContext(), data.colour));
layoutBackground.setCardBackgroundColor(ContextCompat.getColor(getContext(), data.colour));
backupButton.setText(data.buttonText);
backupButton.setBackgroundColor(data.buttonColour);
backupButton.setOnClickListener(v -> { data.callback.BackupClick(data.wallet); });
menuButton.setOnClickListener(v -> {
backupButton.setOnClickListener(v ->
{
data.callback.BackupClick(data.wallet);
});
menuButton.setOnClickListener(v ->
{
showPopup(popupAnchor, data);
});
}
private void showPopup(View view, WarningData data) {
private void showPopup(View view, WarningData data)
{
LayoutInflater inflater = LayoutInflater.from(getContext());
View popupView = inflater.inflate(R.layout.popup_remind_later, null);
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, true);
popupView.setOnClickListener(v -> {
popupView.setOnClickListener(v ->
{
data.callback.remindMeLater(data.wallet);
popupWindow.dismiss();
});
@ -62,7 +71,7 @@ public class WarningHolder extends BinderViewHolder<WarningData>
super(res_id, parent);
title = findViewById(R.id.text_title);
detail = findViewById(R.id.text_detail);
layoutBackground = findViewById(R.id.layout_item_warning);
layoutBackground = findViewById(R.id.card_backup);
backupButton = findViewById(R.id.button_backup);
menuButton = findViewById(R.id.btn_menu);
popupAnchor = findViewById(R.id.popup_anchor);

@ -5,7 +5,6 @@ import android.content.Context;
import android.graphics.Typeface;
import com.google.android.material.tabs.TabLayout;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import android.view.View;
import android.view.ViewGroup;
@ -23,39 +22,7 @@ public class TabUtils {
}
}
public static void setSelectedTabBackground(TabLayout tabLayout, TabLayout.Tab tab, Context context) {
LinearLayout layout = (LinearLayout) ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(tab.getPosition());
TextView tabTextView = (TextView) layout.getChildAt(1);
if (tabTextView != null) {
tabTextView.setTypeface(ResourcesCompat.getFont(context, R.font.font_regular));
tab.view.setBackground(ContextCompat.getDrawable(context, R.drawable.background_round_nofill_8dp));
tab.view.setBackgroundTintList(ContextCompat.getColorStateList(context, R.color.mine));
tabTextView.setTextColor(context.getColor(R.color.white));
}
}
public static void setUnselectedTabBackground(TabLayout tabLayout, TabLayout.Tab tab, Context context) {
LinearLayout layout = (LinearLayout) ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(tab.getPosition());
TextView tabTextView = (TextView) layout.getChildAt(1);
if (tabTextView != null) {
tabTextView.setTypeface(ResourcesCompat.getFont(context, R.font.font_regular));
tab.view.setBackground(ContextCompat.getDrawable(context, R.drawable.background_round_nofill_8dp));
tab.view.setBackgroundTintList(ContextCompat.getColorStateList(context, R.color.white));
tabTextView.setTextColor(context.getColor(R.color.dove));
}
}
public static void decorateTabLayout(Context context, TabLayout tabLayout) {
int tabCount = tabLayout.getTabCount();
if (tabCount > 3) {
View tab = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(tabCount - 1);
ViewGroup.MarginLayoutParams tabParams = (ViewGroup.MarginLayoutParams) tab.getLayoutParams();
tabParams.rightMargin = Utils.dp2px(context, 12);
tab.requestLayout();
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
@ -88,27 +55,5 @@ public class TabUtils {
tabParams.rightMargin = Utils.dp2px(context, 12);
tab.requestLayout();
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
setSelectedTabBackground(tabLayout, tab, context);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
setUnselectedTabBackground(tabLayout, tab, context);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
TabLayout.Tab firstTab = tabLayout.getTabAt(0);
if (firstTab != null) {
TabUtils.setSelectedTabBackground(tabLayout, firstTab, context);
}
}
}

@ -23,6 +23,7 @@ import android.util.Patterns;
import android.util.TypedValue;
import android.webkit.URLUtil;
import androidx.annotation.ColorInt;
import androidx.annotation.RawRes;
import com.alphawallet.app.BuildConfig;
@ -880,4 +881,12 @@ public class Utils {
return cleanInput.length() == 64;
}
public static @ColorInt int getColorFromAttr(Context context, int resId)
{
TypedValue typedValue = new TypedValue();
Resources.Theme theme = context.getTheme();
theme.resolveAttribute(resId, typedValue, true);
return typedValue.data;
}
}

@ -26,54 +26,20 @@ import io.realm.Realm;
@HiltViewModel
public class AdvancedSettingsViewModel extends BaseViewModel {
private final LocaleRepositoryType localeRepository;
private final CurrencyRepositoryType currencyRepository;
private final AssetDefinitionService assetDefinitionService;
private final PreferenceRepositoryType preferenceRepository;
private final TransactionsService transactionsService;
@Inject
AdvancedSettingsViewModel(
LocaleRepositoryType localeRepository,
CurrencyRepositoryType currencyRepository,
AssetDefinitionService assetDefinitionService,
PreferenceRepositoryType preferenceRepository,
TransactionsService transactionsService) {
this.localeRepository = localeRepository;
this.currencyRepository = currencyRepository;
this.assetDefinitionService = assetDefinitionService;
this.preferenceRepository = preferenceRepository;
this.transactionsService = transactionsService;
}
public ArrayList<LocaleItem> getLocaleList(Context context) {
return localeRepository.getLocaleList(context);
}
public void setLocale(Context activity) {
String currentLocale = localeRepository.getActiveLocale();
LocaleUtils.setLocale(activity, currentLocale);
}
public void updateLocale(String newLocale, Context context) {
localeRepository.setUserPreferenceLocale(newLocale);
localeRepository.setLocale(context, newLocale);
}
public String getDefaultCurrency(){
return currencyRepository.getDefaultCurrency();
}
public ArrayList<CurrencyItem> getCurrencyList() {
return currencyRepository.getCurrencyList();
}
public Single<Boolean> updateCurrency(String currencyCode){
currencyRepository.setDefaultCurrency(currencyCode);
//delete tickers from realm
return transactionsService.wipeTickerData();
}
public boolean createDirectory() {
//create XML repository directory
File directory = new File(
@ -94,11 +60,6 @@ public class AdvancedSettingsViewModel extends BaseViewModel {
assetDefinitionService.startAlphaWalletListener();
}
public String getActiveLocale()
{
return localeRepository.getActiveLocale();
}
public void setFullScreenState(boolean state)
{
preferenceRepository.setFullScreenState(state);

@ -21,7 +21,6 @@ import android.widget.Toast;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.alphawallet.app.BuildConfig;
import com.alphawallet.app.C;
import com.alphawallet.app.R;
import com.alphawallet.app.entity.AnalyticsProperties;
@ -458,7 +457,7 @@ public class HomeViewModel extends BaseViewModel {
contentView.setOnCloseActionListener(listener);
dialog = new BottomSheetDialog(activity, R.style.FullscreenBottomSheetDialogStyle);
dialog = new BottomSheetDialog(activity);
dialog.setContentView(contentView);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
@ -578,7 +577,7 @@ public class HomeViewModel extends BaseViewModel {
public void tryToShowEmailPrompt(Context context, View successOverlay, Handler handler, Runnable onSuccessRunnable) {
if (preferenceRepository.getLaunchCount() == 4) {
EmailPromptView emailPromptView = new EmailPromptView(context, successOverlay, handler, onSuccessRunnable);
BottomSheetDialog emailPromptDialog = new BottomSheetDialog(context, R.style.FullscreenBottomSheetDialogStyle);
BottomSheetDialog emailPromptDialog = new BottomSheetDialog(context);
emailPromptDialog.setContentView(emailPromptView);
emailPromptDialog.setCancelable(true);
emailPromptDialog.setCanceledOnTouchOutside(true);
@ -616,7 +615,7 @@ public class HomeViewModel extends BaseViewModel {
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe((releases) -> {
BottomSheetDialog dialog = new BottomSheetDialog(context, R.style.FullscreenBottomSheetDialogStyle);
BottomSheetDialog dialog = new BottomSheetDialog(context);
WhatsNewView view = new WhatsNewView(context, releases, v -> dialog.dismiss());

@ -5,16 +5,25 @@ import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import android.content.Context;
import com.alphawallet.app.entity.CurrencyItem;
import com.alphawallet.app.entity.LocaleItem;
import com.alphawallet.app.entity.Transaction;
import com.alphawallet.app.entity.Wallet;
import com.alphawallet.app.interact.GenericWalletInteract;
import com.alphawallet.app.repository.CurrencyRepositoryType;
import com.alphawallet.app.repository.LocaleRepositoryType;
import com.alphawallet.app.repository.PreferenceRepositoryType;
import com.alphawallet.app.router.ManageWalletsRouter;
import com.alphawallet.app.router.MyAddressRouter;
import com.alphawallet.app.service.TransactionsService;
import com.alphawallet.app.util.LocaleUtils;
import java.util.ArrayList;
import javax.inject.Inject;
import dagger.hilt.android.lifecycle.HiltViewModel;
import io.reactivex.Single;
@HiltViewModel
public class NewSettingsViewModel extends BaseViewModel {
@ -26,17 +35,59 @@ public class NewSettingsViewModel extends BaseViewModel {
private final MyAddressRouter myAddressRouter;
private final ManageWalletsRouter manageWalletsRouter;
private final PreferenceRepositoryType preferenceRepository;
private final LocaleRepositoryType localeRepository;
private final CurrencyRepositoryType currencyRepository;
private final TransactionsService transactionsService;
@Inject
NewSettingsViewModel(
GenericWalletInteract genericWalletInteract,
MyAddressRouter myAddressRouter,
ManageWalletsRouter manageWalletsRouter,
PreferenceRepositoryType preferenceRepository) {
PreferenceRepositoryType preferenceRepository,
LocaleRepositoryType localeRepository,
CurrencyRepositoryType currencyRepository,
TransactionsService transactionsService) {
this.genericWalletInteract = genericWalletInteract;
this.myAddressRouter = myAddressRouter;
this.manageWalletsRouter = manageWalletsRouter;
this.preferenceRepository = preferenceRepository;
this.localeRepository = localeRepository;
this.currencyRepository = currencyRepository;
this.transactionsService = transactionsService;
}
public ArrayList<LocaleItem> getLocaleList(Context context) {
return localeRepository.getLocaleList(context);
}
public void setLocale(Context activity) {
String currentLocale = localeRepository.getActiveLocale();
LocaleUtils.setLocale(activity, currentLocale);
}
public void updateLocale(String newLocale, Context context) {
localeRepository.setUserPreferenceLocale(newLocale);
localeRepository.setLocale(context, newLocale);
}
public String getDefaultCurrency(){
return currencyRepository.getDefaultCurrency();
}
public ArrayList<CurrencyItem> getCurrencyList() {
return currencyRepository.getCurrencyList();
}
public Single<Boolean> updateCurrency(String currencyCode){
currencyRepository.setDefaultCurrency(currencyCode);
//delete tickers from realm
return transactionsService.wipeTickerData();
}
public String getActiveLocale()
{
return localeRepository.getActiveLocale();
}
public void showManageWallets(Context context, boolean clearStack) {

@ -0,0 +1,64 @@
package com.alphawallet.app.viewmodel;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;
import android.app.UiModeManager;
import android.content.Context;
import androidx.appcompat.app.AppCompatDelegate;
import com.alphawallet.app.C;
import com.alphawallet.app.repository.PreferenceRepositoryType;
import javax.inject.Inject;
import dagger.hilt.android.lifecycle.HiltViewModel;
@HiltViewModel
public class SelectThemeViewModel extends BaseViewModel
{
private final PreferenceRepositoryType preferenceRepository;
@Inject
public SelectThemeViewModel(PreferenceRepositoryType preferenceRepository)
{
this.preferenceRepository = preferenceRepository;
}
public int getTheme()
{
return preferenceRepository.getTheme();
}
public void setTheme(Context context, int theme)
{
preferenceRepository.setTheme(theme);
updateTheme(context, theme);
}
private void updateTheme(Context context, int theme)
{
if (theme == C.THEME_LIGHT)
{
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO);
}
else if (theme == C.THEME_DARK)
{
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
}
else
{
UiModeManager uiModeManager = (UiModeManager) context.getSystemService(Context.UI_MODE_SERVICE);
int mode = uiModeManager.getNightMode();
if (mode == UiModeManager.MODE_NIGHT_YES)
{
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
}
else if (mode == UiModeManager.MODE_NIGHT_NO)
{
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO);
}
}
}
}

@ -243,7 +243,7 @@ public class WalletViewModel extends BaseViewModel
context.startActivity(intent);
});
dialog = new BottomSheetDialog(context, R.style.FullscreenBottomSheetDialogStyle);
dialog = new BottomSheetDialog(context);
dialog.setContentView(actionsView);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);

@ -1,10 +1,17 @@
package com.alphawallet.app.web3;
import static androidx.webkit.WebSettingsCompat.FORCE_DARK_OFF;
import static androidx.webkit.WebSettingsCompat.FORCE_DARK_ON;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.webkit.WebSettingsCompat;
import androidx.webkit.WebViewFeature;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.AttributeSet;
@ -121,6 +128,20 @@ public class Web3TokenView extends WebView
+ "AlphaWallet(Platform=Android&AppVersion=" + BuildConfig.VERSION_NAME + ")");
WebView.setWebContentsDebuggingEnabled(true);
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK))
{
switch (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK)
{
case Configuration.UI_MODE_NIGHT_YES:
WebSettingsCompat.setForceDark(getSettings(), FORCE_DARK_ON);
break;
case Configuration.UI_MODE_NIGHT_NO:
case Configuration.UI_MODE_NIGHT_UNDEFINED:
WebSettingsCompat.setForceDark(getSettings(), FORCE_DARK_OFF);
break;
}
}
setScrollBarSize(0);
setVerticalScrollBarEnabled(false);
setScrollContainer(false);

@ -1,16 +1,18 @@
package com.alphawallet.app.web3;
import static androidx.webkit.WebSettingsCompat.FORCE_DARK_OFF;
import static androidx.webkit.WebSettingsCompat.FORCE_DARK_ON;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
@ -18,6 +20,8 @@ import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.webkit.WebSettingsCompat;
import androidx.webkit.WebViewFeature;
import com.alphawallet.app.BuildConfig;
import com.alphawallet.app.entity.URLLoadInterface;
@ -33,9 +37,6 @@ import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
@ -45,48 +46,143 @@ public class Web3View extends WebView {
private static final String JS_PROTOCOL_CANCELLED = "cancelled";
private static final String JS_PROTOCOL_ON_SUCCESSFUL = "AlphaWallet.executeCallback(%1$s, null, \"%2$s\")";
private static final String JS_PROTOCOL_ON_FAILURE = "AlphaWallet.executeCallback(%1$s, \"%2$s\", null)";
private final Web3ViewClient webViewClient;
@Nullable
private OnSignTransactionListener onSignTransactionListener;
private final OnSignTransactionListener innerOnSignTransactionListener = new OnSignTransactionListener() {
@Override
public void onSignTransaction(Web3Transaction transaction, String url)
{
if (onSignTransactionListener != null)
{
onSignTransactionListener.onSignTransaction(transaction, url);
}
}
};
@Nullable
private OnSignMessageListener onSignMessageListener;
private final OnSignMessageListener innerOnSignMessageListener = new OnSignMessageListener() {
@Override
public void onSignMessage(EthereumMessage message)
{
if (onSignMessageListener != null)
{
onSignMessageListener.onSignMessage(message);
}
}
};
@Nullable
private OnSignPersonalMessageListener onSignPersonalMessageListener;
private final OnSignPersonalMessageListener innerOnSignPersonalMessageListener = new OnSignPersonalMessageListener() {
@Override
public void onSignPersonalMessage(EthereumMessage message)
{
onSignPersonalMessageListener.onSignPersonalMessage(message);
}
};
@Nullable
private OnSignTypedMessageListener onSignTypedMessageListener;
private final OnSignTypedMessageListener innerOnSignTypedMessageListener = new OnSignTypedMessageListener() {
@Override
public void onSignTypedMessage(EthereumTypedMessage message)
{
onSignTypedMessageListener.onSignTypedMessage(message);
}
};
@Nullable
private OnEthCallListener onEthCallListener;
private final OnEthCallListener innerOnEthCallListener = new OnEthCallListener() {
@Override
public void onEthCall(Web3Call txData)
{
onEthCallListener.onEthCall(txData);
}
};
@Nullable
private OnWalletAddEthereumChainObjectListener onWalletAddEthereumChainObjectListener;
private final OnWalletAddEthereumChainObjectListener innerAddChainListener = new OnWalletAddEthereumChainObjectListener() {
@Override
public void onWalletAddEthereumChainObject(long callbackId, WalletAddEthereumChainObject chainObject)
{
onWalletAddEthereumChainObjectListener.onWalletAddEthereumChainObject(callbackId, chainObject);
}
};
@Nullable
private OnVerifyListener onVerifyListener;
private final OnVerifyListener innerOnVerifyListener = new OnVerifyListener() {
@Override
public void onVerify(String message, String signHex)
{
if (onVerifyListener != null)
{
onVerifyListener.onVerify(message, signHex);
}
}
};
@Nullable
private OnGetBalanceListener onGetBalanceListener;
private final OnGetBalanceListener innerOnGetBalanceListener = new OnGetBalanceListener() {
@Override
public void onGetBalance(String balance)
{
if (onGetBalanceListener != null)
{
onGetBalanceListener.onGetBalance(balance);
}
}
};
@Nullable
private OnWalletActionListener onWalletActionListener;
private final OnWalletActionListener innerOnWalletActionListener = new OnWalletActionListener() {
@Override
public void onRequestAccounts(long callbackId)
{
onWalletActionListener.onRequestAccounts(callbackId);
}
private final Web3ViewClient webViewClient;
@Override
public void onWalletSwitchEthereumChain(long callbackId, WalletAddEthereumChainObject chainObj)
{
onWalletActionListener.onWalletSwitchEthereumChain(callbackId, chainObj);
}
};
private URLLoadInterface loadInterface;
public Web3View(@NonNull Context context, @Nullable AttributeSet attrs) {
public Web3View(@NonNull Context context, @Nullable AttributeSet attrs)
{
super(context, attrs);
webViewClient = new Web3ViewClient(getContext());
init();
}
public Web3View(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
public Web3View(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
webViewClient = new Web3ViewClient(getContext());
init();
}
private static boolean isJson(String value)
{
try
{
JSONObject stateData = new JSONObject(value);
return true;
} catch (Exception e)
{
return false;
}
}
@Override
public void setWebChromeClient(WebChromeClient client) {
public void setWebChromeClient(WebChromeClient client)
{
super.setWebChromeClient(client);
}
@Override
public void setWebViewClient(WebViewClient client) {
public void setWebViewClient(WebViewClient client)
{
super.setWebViewClient(new WrapWebViewClient(webViewClient, client));
}
@ -120,7 +216,8 @@ public class Web3View extends WebView {
}
@SuppressLint("SetJavaScriptEnabled")
public void init() {
public void init()
{
getSettings().setJavaScriptEnabled(true);
getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
getSettings().setBuiltInZoomControls(true);
@ -130,7 +227,7 @@ public class Web3View extends WebView {
getSettings().setDomStorageEnabled(true);
getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
getSettings().setUserAgentString(getSettings().getUserAgentString()
+ "AlphaWallet(Platform=Android&AppVersion=" + BuildConfig.VERSION_NAME + ")");
+ "AlphaWallet(Platform=Android&AppVersion=" + BuildConfig.VERSION_NAME + ")");
WebView.setWebContentsDebuggingEnabled(true); //so devs can debug their scripts/pages
addJavascriptInterface(new SignCallbackJSInterface(
this,
@ -141,27 +238,41 @@ public class Web3View extends WebView {
innerOnEthCallListener,
innerAddChainListener,
innerOnWalletActionListener), "alpha");
}
public void setWalletAddress(@NonNull Address address) {
webViewClient.getJsInjectorClient().setWalletAddress(address);
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK))
{
switch (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK)
{
case Configuration.UI_MODE_NIGHT_YES:
WebSettingsCompat.setForceDark(getSettings(), FORCE_DARK_ON);
break;
case Configuration.UI_MODE_NIGHT_NO:
case Configuration.UI_MODE_NIGHT_UNDEFINED:
WebSettingsCompat.setForceDark(getSettings(), FORCE_DARK_OFF);
break;
}
}
}
@Nullable
public Address getWalletAddress() {
public Address getWalletAddress()
{
return webViewClient.getJsInjectorClient().getWalletAddress();
}
public void setChainId(long chainId) {
webViewClient.getJsInjectorClient().setChainId(chainId);
public void setWalletAddress(@NonNull Address address)
{
webViewClient.getJsInjectorClient().setWalletAddress(address);
}
public long getChainId() {
public long getChainId()
{
return webViewClient.getJsInjectorClient().getChainId();
}
public void setRpcUrl(@NonNull String rpcUrl) {
webViewClient.getJsInjectorClient().setRpcUrl(rpcUrl);
public void setChainId(long chainId)
{
webViewClient.getJsInjectorClient().setChainId(chainId);
}
public void setWebLoadCallback(URLLoadInterface iFace)
@ -170,180 +281,124 @@ public class Web3View extends WebView {
}
@Nullable
public String getRpcUrl() {
public String getRpcUrl()
{
return webViewClient.getJsInjectorClient().getRpcUrl();
}
public void addUrlHandler(@NonNull UrlHandler urlHandler) {
public void setRpcUrl(@NonNull String rpcUrl)
{
webViewClient.getJsInjectorClient().setRpcUrl(rpcUrl);
}
public void addUrlHandler(@NonNull UrlHandler urlHandler)
{
webViewClient.addUrlHandler(urlHandler);
}
public void removeUrlHandler(@NonNull UrlHandler urlHandler) {
public void removeUrlHandler(@NonNull UrlHandler urlHandler)
{
webViewClient.removeUrlHandler(urlHandler);
}
public void setOnSignTransactionListener(@Nullable OnSignTransactionListener onSignTransactionListener) {
public void setOnSignTransactionListener(@Nullable OnSignTransactionListener onSignTransactionListener)
{
this.onSignTransactionListener = onSignTransactionListener;
}
public void setOnSignMessageListener(@Nullable OnSignMessageListener onSignMessageListener) {
public void setOnSignMessageListener(@Nullable OnSignMessageListener onSignMessageListener)
{
this.onSignMessageListener = onSignMessageListener;
}
public void setOnSignPersonalMessageListener(@Nullable OnSignPersonalMessageListener onSignPersonalMessageListener) {
public void setOnSignPersonalMessageListener(@Nullable OnSignPersonalMessageListener onSignPersonalMessageListener)
{
this.onSignPersonalMessageListener = onSignPersonalMessageListener;
}
public void setOnSignTypedMessageListener(@Nullable OnSignTypedMessageListener onSignTypedMessageListener) {
public void setOnSignTypedMessageListener(@Nullable OnSignTypedMessageListener onSignTypedMessageListener)
{
this.onSignTypedMessageListener = onSignTypedMessageListener;
}
public void setOnEthCallListener(@Nullable OnEthCallListener onEthCallListener) {
public void setOnEthCallListener(@Nullable OnEthCallListener onEthCallListener)
{
this.onEthCallListener = onEthCallListener;
}
public void setOnWalletAddEthereumChainObjectListener(@Nullable OnWalletAddEthereumChainObjectListener onWalletAddEthereumChainObjectListener) {
public void setOnWalletAddEthereumChainObjectListener(@Nullable OnWalletAddEthereumChainObjectListener onWalletAddEthereumChainObjectListener)
{
this.onWalletAddEthereumChainObjectListener = onWalletAddEthereumChainObjectListener;
}
public void setOnWalletActionListener(@Nullable OnWalletActionListener onWalletActionListener) {
public void setOnWalletActionListener(@Nullable OnWalletActionListener onWalletActionListener)
{
this.onWalletActionListener = onWalletActionListener;
}
public void setOnVerifyListener(@Nullable OnVerifyListener onVerifyListener) {
public void setOnVerifyListener(@Nullable OnVerifyListener onVerifyListener)
{
this.onVerifyListener = onVerifyListener;
}
public void setOnGetBalanceListener(@Nullable OnGetBalanceListener onGetBalanceListener) {
public void setOnGetBalanceListener(@Nullable OnGetBalanceListener onGetBalanceListener)
{
this.onGetBalanceListener = onGetBalanceListener;
}
public void onSignTransactionSuccessful(Web3Transaction transaction, String signHex) {
public void onSignTransactionSuccessful(Web3Transaction transaction, String signHex)
{
long callbackId = transaction.leafPosition;
callbackToJS(callbackId, JS_PROTOCOL_ON_SUCCESSFUL, signHex);
}
public void onSignMessageSuccessful(Signable message, String signHex) {
public void onSignMessageSuccessful(Signable message, String signHex)
{
long callbackId = message.getCallbackId();
callbackToJS(callbackId, JS_PROTOCOL_ON_SUCCESSFUL, signHex);
}
public void onCallFunctionSuccessful(long callbackId, String result) {
public void onCallFunctionSuccessful(long callbackId, String result)
{
callbackToJS(callbackId, JS_PROTOCOL_ON_SUCCESSFUL, result);
}
public void onCallFunctionError(long callbackId, String error) {
public void onCallFunctionError(long callbackId, String error)
{
callbackToJS(callbackId, JS_PROTOCOL_ON_FAILURE, error);
}
public void onSignError(Web3Transaction transaction, String error) {
public void onSignError(Web3Transaction transaction, String error)
{
long callbackId = transaction.leafPosition;
callbackToJS(callbackId, JS_PROTOCOL_ON_FAILURE, error);
}
public void onSignError(EthereumMessage message, String error) {
public void onSignError(EthereumMessage message, String error)
{
long callbackId = message.leafPosition;
callbackToJS(callbackId, JS_PROTOCOL_ON_FAILURE, error);
}
public void onSignCancel(long callbackId) {
public void onSignCancel(long callbackId)
{
callbackToJS(callbackId, JS_PROTOCOL_ON_FAILURE, JS_PROTOCOL_CANCELLED);
}
private void callbackToJS(long callbackId, String function, String param) {
private void callbackToJS(long callbackId, String function, String param)
{
String callback = String.format(function, callbackId, param);
post(() -> evaluateJavascript(callback, value ->Timber.tag("WEB_VIEW").d(value)));
}
public void onWalletActionSuccessful(long callbackId, String message) {
public void onWalletActionSuccessful(long callbackId, String message)
{
String callback = String.format(JS_PROTOCOL_ON_SUCCESSFUL, callbackId, message);
post(() -> {
evaluateJavascript(callback, Timber::d);
});
}
private final OnSignTransactionListener innerOnSignTransactionListener = new OnSignTransactionListener() {
@Override
public void onSignTransaction(Web3Transaction transaction, String url) {
if (onSignTransactionListener != null) {
onSignTransactionListener.onSignTransaction(transaction, url);
}
}
};
private final OnSignMessageListener innerOnSignMessageListener = new OnSignMessageListener() {
@Override
public void onSignMessage(EthereumMessage message) {
if (onSignMessageListener != null) {
onSignMessageListener.onSignMessage(message);
}
}
};
private final OnSignPersonalMessageListener innerOnSignPersonalMessageListener = new OnSignPersonalMessageListener() {
@Override
public void onSignPersonalMessage(EthereumMessage message) {
onSignPersonalMessageListener.onSignPersonalMessage(message);
}
};
private final OnSignTypedMessageListener innerOnSignTypedMessageListener = new OnSignTypedMessageListener() {
@Override
public void onSignTypedMessage(EthereumTypedMessage message) {
onSignTypedMessageListener.onSignTypedMessage(message);
}
};
private final OnEthCallListener innerOnEthCallListener = new OnEthCallListener()
{
@Override
public void onEthCall(Web3Call txData)
{
onEthCallListener.onEthCall(txData);
}
};
private final OnWalletAddEthereumChainObjectListener innerAddChainListener = new OnWalletAddEthereumChainObjectListener()
{
@Override
public void onWalletAddEthereumChainObject(long callbackId, WalletAddEthereumChainObject chainObject)
{
onWalletAddEthereumChainObjectListener.onWalletAddEthereumChainObject(callbackId, chainObject);
}
};
private final OnWalletActionListener innerOnWalletActionListener = new OnWalletActionListener() {
@Override
public void onRequestAccounts(long callbackId)
{
onWalletActionListener.onRequestAccounts(callbackId);
}
@Override
public void onWalletSwitchEthereumChain(long callbackId, WalletAddEthereumChainObject chainObj)
{
onWalletActionListener.onWalletSwitchEthereumChain(callbackId, chainObj);
}
};
private final OnVerifyListener innerOnVerifyListener = new OnVerifyListener() {
@Override
public void onVerify(String message, String signHex) {
if (onVerifyListener != null) {
onVerifyListener.onVerify(message, signHex);
}
}
};
private final OnGetBalanceListener innerOnGetBalanceListener = new OnGetBalanceListener() {
@Override
public void onGetBalance(String balance) {
if (onGetBalanceListener != null) {
onGetBalanceListener.onGetBalance(balance);
}
}
};
public void resetView()
{
webViewClient.resetInject();
@ -355,13 +410,15 @@ public class Web3View extends WebView {
private boolean loadingError = false;
private boolean redirect = false;
public WrapWebViewClient(Web3ViewClient internalClient, WebViewClient externalClient) {
public WrapWebViewClient(Web3ViewClient internalClient, WebViewClient externalClient)
{
this.internalClient = internalClient;
this.externalClient = externalClient;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
clearCache(true);
if (!redirect)
@ -375,12 +432,16 @@ public class Web3View extends WebView {
}
@Override
public void onPageFinished(WebView view, String url) {
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
if (!redirect && !loadingError)
{
if (loadInterface != null) { loadInterface.onWebpageLoaded(url, view.getTitle()); }
if (loadInterface != null)
{
loadInterface.onWebpageLoaded(url, view.getTitle());
}
}
else if (!loadingError && loadInterface != null)
{
@ -392,7 +453,8 @@ public class Web3View extends WebView {
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
redirect = true;
return externalClient.shouldOverrideUrlLoading(view, url)
@ -400,7 +462,8 @@ public class Web3View extends WebView {
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error)
{
loadingError = true;
if (externalClient != null)
externalClient.onReceivedError(view, request, error);
@ -408,20 +471,12 @@ public class Web3View extends WebView {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
{
redirect = true;
return externalClient.shouldOverrideUrlLoading(view, request)
|| internalClient.shouldOverrideUrlLoading(view, request);
}
}
private static boolean isJson(String value) {
try {
JSONObject stateData = new JSONObject(value);
return true;
} catch (Exception e) {
return false;
}
}
}

@ -1,159 +1,163 @@
package com.alphawallet.app.widget;
import static com.alphawallet.app.entity.WalletPage.ACTIVITY;
import static com.alphawallet.app.entity.WalletPage.DAPP_BROWSER;
import static com.alphawallet.app.entity.WalletPage.SETTINGS;
import static com.alphawallet.app.entity.WalletPage.WALLET;
import android.content.Context;
import androidx.annotation.Nullable;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.core.content.res.ResourcesCompat;
import com.alphawallet.app.R;
import com.alphawallet.app.entity.WalletPage;
import java.util.ArrayList;
import static com.alphawallet.app.entity.WalletPage.ACTIVITY;
import static com.alphawallet.app.entity.WalletPage.DAPP_BROWSER;
import static com.alphawallet.app.entity.WalletPage.SETTINGS;
import static com.alphawallet.app.entity.WalletPage.WALLET;
public class AWalletBottomNavigationView extends LinearLayout {
private final ImageView dappBrowser;
private final ImageView wallet;
private final ImageView settings;
private final ImageView activity;
public class AWalletBottomNavigationView extends LinearLayout
{
private final TextView dappBrowserLabel;
private final TextView walletLabel;
private final TextView settingsLabel;
private final TextView settingsBadge;
private final TextView settingsLabel;
private final RelativeLayout settingsTab;
private final TextView activityLabel;
private final Typeface regularTypeface;
private final Typeface semiboldTypeface;
private final ArrayList<String> settingsBadgeKeys = new ArrayList<>();
private OnBottomNavigationItemSelectedListener listener;
private WalletPage selectedItem;
private final ArrayList<String> settingsBadgeKeys = new ArrayList<>();
public AWalletBottomNavigationView(Context context, @Nullable AttributeSet attrs) {
public AWalletBottomNavigationView(Context context, @Nullable AttributeSet attrs)
{
super(context, attrs);
inflate(context, R.layout.layout_bottom_navigation, this);
dappBrowser = findViewById(R.id.nav_browser);
wallet = findViewById(R.id.nav_wallet);
settings = findViewById(R.id.nav_settings);
activity = findViewById(R.id.nav_activity);
dappBrowserLabel = findViewById(R.id.nav_browser_text);
walletLabel = findViewById(R.id.nav_wallet_text);
activityLabel = findViewById(R.id.nav_activity_text);
dappBrowserLabel = findViewById(R.id.nav_browser_text);
settingsTab = findViewById(R.id.settings_tab);
settingsLabel = findViewById(R.id.nav_settings_text);
settingsBadge = findViewById(R.id.settings_badge);
activityLabel = findViewById(R.id.nav_activity_text);
//TODO: Refactor with click overlay
findViewById(R.id.wallet_tab).setOnClickListener(v -> selectItem(WALLET));
findViewById(R.id.browser_tab).setOnClickListener(v -> selectItem(DAPP_BROWSER));
findViewById(R.id.settings_tab).setOnClickListener(v -> selectItem(SETTINGS));
findViewById(R.id.activity_tab).setOnClickListener(v -> selectItem(ACTIVITY));
dappBrowser.setOnClickListener(v -> selectItem(DAPP_BROWSER));
wallet.setOnClickListener(v -> selectItem(WALLET));
settings.setOnClickListener(v -> selectItem(SETTINGS));
activity.setOnClickListener(v -> selectItem(ACTIVITY));
dappBrowserLabel.setOnClickListener(v -> selectItem(DAPP_BROWSER));
walletLabel.setOnClickListener(v -> selectItem(WALLET));
settingsLabel.setOnClickListener(v -> selectItem(SETTINGS));
activityLabel.setOnClickListener(v -> selectItem(ACTIVITY));
dappBrowserLabel.setOnClickListener(v -> selectItem(DAPP_BROWSER));
settingsTab.setOnClickListener(v -> selectItem(SETTINGS));
regularTypeface = ResourcesCompat.getFont(getContext(), R.font.font_regular);
semiboldTypeface = ResourcesCompat.getFont(getContext(), R.font.font_semibold);
// set wallet fragment selected on start
setSelectedItem(WALLET);
}
public void setListener(OnBottomNavigationItemSelectedListener listener) {
public void setListener(OnBottomNavigationItemSelectedListener listener)
{
this.listener = listener;
}
private void selectItem(WalletPage index) {
private void selectItem(WalletPage index)
{
listener.onBottomNavigationItemSelected(index);
}
public void setSelectedItem(WalletPage index) {
public WalletPage getSelectedItem()
{
return selectedItem;
}
public void setSelectedItem(WalletPage index)
{
deselectAll();
selectedItem = index;
switch (index) {
switch (index)
{
case DAPP_BROWSER:
dappBrowser.setImageResource(R.drawable.ic_tab_browser_active);
dappBrowserLabel.setTextColor(getResources().getColor(R.color.colorHighlight, getContext().getTheme()));
dappBrowserLabel.setSelected(true);
dappBrowserLabel.setTypeface(semiboldTypeface);
break;
case WALLET:
wallet.setImageResource(R.drawable.ic_tab_wallet_active);
walletLabel.setTextColor(getResources().getColor(R.color.colorHighlight, getContext().getTheme()));
walletLabel.setSelected(true);
walletLabel.setTypeface(semiboldTypeface);
break;
case SETTINGS:
settings.setImageResource(R.drawable.ic_tab_settings_active);
settingsLabel.setTextColor(getResources().getColor(R.color.colorHighlight, getContext().getTheme()));
settingsLabel.setSelected(true);
settingsLabel.setTypeface(semiboldTypeface);
break;
case ACTIVITY:
activity.setImageResource(R.drawable.ic_tab_activity_active);
activityLabel.setTextColor(getResources().getColor(R.color.colorHighlight, getContext().getTheme()));
activityLabel.setSelected(true);
activityLabel.setTypeface(semiboldTypeface);
break;
}
}
public WalletPage getSelectedItem() {
return selectedItem;
}
private void deselectAll() {
dappBrowser.setImageResource(R.drawable.ic_tab_browser);
wallet.setImageResource(R.drawable.ic_tab_wallet);
settings.setImageResource(R.drawable.ic_tab_settings);
activity.setImageResource(R.drawable.ic_tab_activity);
//reset text colour
dappBrowserLabel.setTextColor(getContext().getColor(R.color.dove));
walletLabel.setTextColor(getContext().getColor(R.color.dove));
settingsLabel.setTextColor(getContext().getColor(R.color.dove));
activityLabel.setTextColor(getContext().getColor(R.color.dove));
}
public interface OnBottomNavigationItemSelectedListener {
boolean onBottomNavigationItemSelected(WalletPage index);
private void deselectAll()
{
dappBrowserLabel.setSelected(false);
dappBrowserLabel.setTypeface(regularTypeface);
walletLabel.setSelected(false);
walletLabel.setTypeface(regularTypeface);
settingsLabel.setSelected(false);
settingsLabel.setTypeface(regularTypeface);
activityLabel.setSelected(false);
activityLabel.setTypeface(regularTypeface);
}
public void setSettingsBadgeCount(int count) {
if (count > 0) {
public void setSettingsBadgeCount(int count)
{
if (count > 0)
{
settingsBadge.setVisibility(View.VISIBLE);
} else {
}
else
{
settingsBadge.setVisibility(View.GONE);
}
settingsBadge.setText(String.valueOf(count));
}
public void addSettingsBadgeKey(String key) {
if (!settingsBadgeKeys.contains(key)) {
public void addSettingsBadgeKey(String key)
{
if (!settingsBadgeKeys.contains(key))
{
settingsBadgeKeys.add(key);
}
showOrHideSettingsBadge();
}
public void removeSettingsBadgeKey(String key) {
public void removeSettingsBadgeKey(String key)
{
settingsBadgeKeys.remove(key);
showOrHideSettingsBadge();
}
private void showOrHideSettingsBadge() {
if (settingsBadgeKeys.size() > 0) {
private void showOrHideSettingsBadge()
{
if (settingsBadgeKeys.size() > 0)
{
settingsBadge.setVisibility(View.VISIBLE);
} else {
}
else
{
settingsBadge.setVisibility(View.GONE);
}
settingsBadge.setText(String.valueOf(settingsBadgeKeys.size()));
}
public void hideBrowserTab() {
LinearLayout browserTab = findViewById(R.id.browser_tab);
if (browserTab != null) browserTab.setVisibility(View.GONE);
public void hideBrowserTab()
{
if (dappBrowserLabel != null) dappBrowserLabel.setVisibility(View.GONE);
}
public interface OnBottomNavigationItemSelectedListener
{
boolean onBottomNavigationItemSelected(WalletPage index);
}
}

@ -103,9 +103,4 @@ public class AWalletConfirmationDialog extends Dialog {
extraText.setVisibility(View.VISIBLE);
extraText.setText(context.getResources().getString(resId));
}
public void showShareLink() {
ImageView shareIcon = findViewById(R.id.image_share);
shareIcon.setVisibility(View.VISIBLE);
}
}

@ -45,8 +45,6 @@ import io.realm.Realm;
import static com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_EXPANDED;
import org.w3c.dom.Text;
/**
* Created by JB on 17/11/2020.
*/
@ -81,7 +79,7 @@ public class ActionSheetDialog extends BottomSheetDialog implements StandardFunc
String destName, String destAddress, TokensService ts,
ActionSheetCallback aCallBack)
{
super(activity, R.style.FullscreenBottomSheetDialogStyle);
super(activity);
View view = View.inflate(getContext(), R.layout.dialog_action_sheet, null);
setContentView(view);

@ -21,6 +21,7 @@ import com.alphawallet.app.repository.entity.RealmTransaction;
import com.alphawallet.app.repository.entity.RealmTransfer;
import com.alphawallet.app.service.TokensService;
import com.alphawallet.app.ui.widget.adapter.ActivityAdapter;
import com.alphawallet.app.ui.widget.divider.ListDivider;
import com.alphawallet.app.ui.widget.entity.TokenTransferData;
import java.math.BigInteger;
@ -59,6 +60,7 @@ public class ActivityHistoryList extends LinearLayout
recentTransactionsView = findViewById(R.id.list);
recentTransactionsView.setLayoutManager(new LinearLayoutManager(getContext()));
recentTransactionsView.addItemDecoration(new ListDivider(getContext()));
loadingTransactions = findViewById(R.id.loading_transactions);
noTxNotice = findViewById(R.id.layout_no_recent_transactions);
this.context = context;

@ -10,8 +10,9 @@ import android.widget.ImageView;
import com.alphawallet.token.entity.SigReturnType;
import com.alphawallet.token.entity.XMLDsigDescriptor;
import com.alphawallet.app.R;
import com.google.android.material.appbar.MaterialToolbar;
public class CertifiedToolbarView extends androidx.appcompat.widget.Toolbar
public class CertifiedToolbarView extends MaterialToolbar
{
private Activity activity;
private AWalletAlertDialog dialog;

@ -4,7 +4,6 @@ import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.ImageView;
@ -13,20 +12,16 @@ import android.widget.TextView;
import android.widget.Toast;
import com.alphawallet.app.R;
import org.web3j.crypto.WalletUtils;
import com.google.android.material.button.MaterialButton;
public class CopyTextView extends LinearLayout {
public static final String KEY_ADDRESS = "key_address";
private final Context context;
private ImageView copy;
private TextView text;
private LinearLayout layout;
private MaterialButton button;
private int textResId;
private int textColor;
private int gravity;
private boolean showToast;
private boolean boldFont;
@ -34,7 +29,8 @@ public class CopyTextView extends LinearLayout {
private String rawAddress;
private float marginRight;
public CopyTextView(Context context, AttributeSet attrs) {
public CopyTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
this.context = context;
@ -45,75 +41,82 @@ public class CopyTextView extends LinearLayout {
bindViews();
}
private void getAttrs(Context context, AttributeSet attrs) {
private void getAttrs(Context context, AttributeSet attrs)
{
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.CopyTextView,
0, 0
);
try {
try
{
textResId = a.getResourceId(R.styleable.CopyTextView_text, R.string.action_add_wallet);
textColor = a.getColor(R.styleable.CopyTextView_textColour, context.getColor(R.color.mine));
gravity = a.getInt(R.styleable.CopyTextView_android_gravity, Gravity.NO_GRAVITY);
showToast = a.getBoolean(R.styleable.CopyTextView_showToast, true);
boldFont = a.getBoolean(R.styleable.CopyTextView_bold, false);
removePadding = a.getBoolean(R.styleable.CopyTextView_removePadding, false);
marginRight = a.getDimension(R.styleable.CopyTextView_marginRight, 0.0f);
} finally {
} finally
{
a.recycle();
}
}
private void bindViews() {
layout = findViewById(R.id.view_container);
copy = findViewById(R.id.img_copy);
text = findViewById(R.id.text);
text.setText(textResId);
text.setTextColor(textColor);
text.setGravity(gravity);
LayoutParams layoutParams = (LayoutParams) text.getLayoutParams();
layoutParams.rightMargin = (int) marginRight;
text.setLayoutParams(layoutParams);
if(boldFont)
{
text.setTypeface(text.getTypeface(), Typeface.BOLD);
}
if(removePadding)
{
copy.setPadding(0, 0, 0, 0);
}
layout.setOnClickListener(v -> copyToClipboard());
copy.setOnClickListener(v -> copyToClipboard());
private void bindViews()
{
button = findViewById(R.id.button);
button.setText(textResId);
// text.setText(textResId);
// text.setTextColor(textColor);
// text.setGravity(gravity);
// LayoutParams layoutParams = (LayoutParams) text.getLayoutParams();
// layoutParams.rightMargin = (int) marginRight;
// text.setLayoutParams(layoutParams);
// if(boldFont)
// {
// text.setTypeface(text.getTypeface(), Typeface.BOLD);
// }
//
// if(removePadding)
// {
// copy.setPadding(0, 0, 0, 0);
// }
button.setOnClickListener(v -> copyToClipboard());
// copy.setOnClickListener(v -> copyToClipboard());
}
public String getText() {
public String getText()
{
return rawAddress;
}
public void setText(CharSequence text) {
rawAddress = text.toString();
String breakAddr = rawAddress;
if ((gravity & Gravity.CENTER_HORIZONTAL) == Gravity.CENTER_HORIZONTAL && WalletUtils.isValidAddress(breakAddr)) //split string across two lines
{
breakAddr = breakAddr.substring(0, 22) + " " + breakAddr.substring(22);
}
this.text.setText(breakAddr);
public void setText(CharSequence text)
{
// rawAddress = text.toString();
// String breakAddr = rawAddress;
// if ((gravity & Gravity.CENTER_HORIZONTAL) == Gravity.CENTER_HORIZONTAL && WalletUtils.isValidAddress(breakAddr)) //split string across two lines
// {
// breakAddr = breakAddr.substring(0, 22) + " " + breakAddr.substring(22);
// }
//
// this.button.setText(breakAddr);
this.button.setText(text.toString());
}
private void copyToClipboard()
{
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(KEY_ADDRESS, rawAddress);
if (clipboard != null) {
if (clipboard != null)
{
clipboard.setPrimaryClip(clip);
}
if(showToast) Toast.makeText(context, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
if (showToast)
Toast.makeText(context, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
}
}

@ -1,81 +0,0 @@
package com.alphawallet.app.widget;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import com.alphawallet.app.ui.widget.OnDepositClickListener;
import com.alphawallet.app.R;
import com.alphawallet.app.entity.Wallet;
public class DepositView extends FrameLayout implements View.OnClickListener {
private static final String coinbaseUrl = "https://buy.coinbase.com/";
private static final String localethereum = "https://localethereum.com/";
private static final String changelly = "https://payments.changelly.com/?crypto=ETH&amount=0";
private final Context context;
private OnDepositClickListener onDepositClickListener;
@NonNull
private Wallet wallet;
public DepositView(Context context, @NonNull Wallet wallet) {
this(context, R.layout.layout_dialog_deposit, wallet);
}
public DepositView(Context context, @LayoutRes int layoutId, @NonNull Wallet wallet) {
super(context);
this.context = context;
init(layoutId, wallet);
}
private void init(@LayoutRes int layoutId, @NonNull Wallet wallet) {
this.wallet = wallet;
LayoutInflater.from(getContext()).inflate(layoutId, this, true);
findViewById(R.id.action_coinbase).setOnClickListener(this);
findViewById(R.id.action_localeth).setOnClickListener(this);
findViewById(R.id.action_changelly).setOnClickListener(this);
}
/**
* After user selects where they want to buy, open Dapp browser at the site
* @param v
*/
@Override
public void onClick(View v) {
String url;
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
String userCurrency = pref.getString("currency_locale", "USD");
final int action_localeth = R.id.action_localeth;
final int action_changelly = R.id.action_changelly;
final int action_coinbase = R.id.action_coinbase;
switch (v.getId()) {
case action_localeth: {
url = localethereum;
} break;
case action_changelly: {
url = changelly + "&fiat=" + userCurrency;
} break;
default:
case action_coinbase: {
url = coinbaseUrl;
} break;
}
if (onDepositClickListener != null) {
onDepositClickListener.onDepositClick(v, url);
}
}
public void setOnDepositClickListener(OnDepositClickListener onDepositClickListener) {
this.onDepositClickListener = onDepositClickListener;
}
}

@ -39,7 +39,7 @@ public class DialogInfoItem extends LinearLayout {
boolean showAction = a.getBoolean(R.styleable.DialogInfoItem_showActionText, false);
setLabel(a.getString(R.styleable.DialogInfoItem_title));
setMessage(a.getString(R.styleable.DialogInfoItem_text));
actionText.setVisibility( showAction ? VISIBLE : GONE);
actionText.setVisibility( showAction ? VISIBLE : INVISIBLE);
}
public void setLabel(String label) {

@ -1,67 +0,0 @@
package com.alphawallet.app.widget;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.alphawallet.app.R;
public class FilterDialog extends Dialog {
private final Spinner spinnerDate;
private final Spinner spinnerPrice;
private final Spinner spinnerTimeframe;
private final Spinner spinnerDistance;
private final Button btnApply;
public FilterDialog(Activity activity) {
super(activity);
setupDialog();
spinnerDate = findViewById(R.id.spinner_date);
spinnerDate.setAdapter(createAdapter(activity, R.array.filter_date));
spinnerPrice = findViewById(R.id.spinner_price);
spinnerPrice.setAdapter(createAdapter(activity, R.array.filter_price));
spinnerDistance = findViewById(R.id.spinner_distance);
spinnerDistance.setAdapter(createAdapter(activity, R.array.filter_distance));
spinnerTimeframe = findViewById(R.id.spinner_timeframe);
spinnerTimeframe.setAdapter(createAdapter(activity, R.array.filter_timeframe));
btnApply = findViewById(R.id.btn_filter);
btnApply.setOnClickListener(v -> {
filter();
dismiss();
});
}
private void setupDialog() {
setContentView(R.layout.dialog_filter);
setCanceledOnTouchOutside(true);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
setCanceledOnTouchOutside(true);
getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
private void filter() {
//TODO: Filter action
// int dateFilterId = (int) spinnerDate.getSelectedItemId();
// int priceFilterId = (int) spinnerPrice.getSelectedItemId();
// int distanceFilterId = (int) spinnerDistance.getSelectedItemId();
// int timeframeFilterId = (int) spinnerTimeframe.getSelectedItemId();
}
private ArrayAdapter<CharSequence> createAdapter(Activity activity, int resId) {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(activity, resId, R.layout.item_spinner);
adapter.setDropDownViewResource(R.layout.item_spinner_dropdown);
return adapter;
}
}

@ -1,5 +1,13 @@
package com.alphawallet.app.widget;
import static android.os.VibrationEffect.DEFAULT_AMPLITUDE;
import static com.alphawallet.ethereum.EthereumNetworkBase.ARBITRUM_MAIN_ID;
import static com.alphawallet.ethereum.EthereumNetworkBase.BINANCE_MAIN_ID;
import static com.alphawallet.ethereum.EthereumNetworkBase.MAINNET_ID;
import static com.alphawallet.ethereum.EthereumNetworkBase.MATIC_ID;
import static com.alphawallet.ethereum.EthereumNetworkBase.OPTIMISTIC_MAIN_ID;
import static com.alphawallet.ethereum.EthereumNetworkBase.XDAI_ID;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
@ -16,7 +24,6 @@ import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
@ -44,6 +51,7 @@ import com.alphawallet.app.util.Utils;
import com.alphawallet.token.entity.TSAction;
import com.alphawallet.token.tools.TokenDefinition;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.button.MaterialButton;
import org.jetbrains.annotations.NotNull;
@ -58,16 +66,10 @@ import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;
import static android.os.VibrationEffect.DEFAULT_AMPLITUDE;
import static com.alphawallet.ethereum.EthereumNetworkBase.ARBITRUM_MAIN_ID;
import static com.alphawallet.ethereum.EthereumNetworkBase.BINANCE_MAIN_ID;
import static com.alphawallet.ethereum.EthereumNetworkBase.MAINNET_ID;
import static com.alphawallet.ethereum.EthereumNetworkBase.MATIC_ID;
import static com.alphawallet.ethereum.EthereumNetworkBase.OPTIMISTIC_MAIN_ID;
import static com.alphawallet.ethereum.EthereumNetworkBase.XDAI_ID;
public class FunctionButtonBar extends LinearLayout implements AdapterView.OnItemClickListener, TokensAdapterCallback, View.OnClickListener {
public class FunctionButtonBar extends LinearLayout implements AdapterView.OnItemClickListener, TokensAdapterCallback {
private final Context context;
private final Handler handler = new Handler(Looper.getMainLooper());
private final Semaphore functionMapComplete = new Semaphore(1);
private Map<String, TSAction> functions;
private NonFungibleAdapterInterface adapter;
private List<BigInteger> selection = new ArrayList<>();
@ -76,22 +78,17 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
private int buttonCount;
private Token token = null;
private boolean showButtons = false;
private Button primaryButton;
private Button secondaryButton;
private MaterialButton primaryButton;
private MaterialButton secondaryButton;
private RelativeLayout primaryButtonWrapper;
private ProgressBar primaryButtonSpinner;
private ImageButton moreButton;
private final Handler handler = new Handler(Looper.getMainLooper());
private MaterialButton moreButton;
private AssetDefinitionService assetService;
private WalletType walletType = WalletType.NOT_DEFINED;
private BottomSheetDialog bottomSheet;
private ListView moreActionsListView;
private List<ItemClick> moreActionsList;
private FunctionItemAdapter moreActionsAdapter;
private final Semaphore functionMapComplete = new Semaphore(1);
private boolean hasBuyFunction;
private OnRampRepositoryType onRampRepository;
@ -111,7 +108,7 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
secondaryButton = findViewById(R.id.secondary_button);
moreButton = findViewById(R.id.more_button);
bottomSheet = new BottomSheetDialog(getContext(), R.style.FullscreenBottomSheetDialogStyle);
bottomSheet = new BottomSheetDialog(getContext());
bottomSheet.setCancelable(true);
bottomSheet.setCanceledOnTouchOutside(true);
moreActionsListView = new ListView(getContext());
@ -121,11 +118,12 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
moreActionsListView.setAdapter(moreActionsAdapter);
bottomSheet.setContentView(moreActionsListView);
moreActionsListView.setOnItemClickListener(this);
moreActionsListView.setDivider(new ColorDrawable(ContextCompat.getColor(context, R.color.mercury)));
moreActionsListView.setDivider(new ColorDrawable(Utils.getColorFromAttr(getContext(), R.attr.colorSurfaceQuaternary)));
moreActionsListView.setDividerHeight(Utils.dp2px(context, 1));
}
private void resetButtonCount() {
private void resetButtonCount()
{
buttonCount = 0;
primaryButtonWrapper.setVisibility(View.GONE);
secondaryButton.setVisibility(View.GONE);
@ -134,13 +132,15 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
moreActionsAdapter.notifyDataSetChanged();
}
public void setupFunctions(StandardFunctionInterface functionInterface, List<Integer> functionResources) {
public void setupFunctions(StandardFunctionInterface functionInterface, List<Integer> functionResources)
{
callStandardFunctions = functionInterface;
adapter = null;
functions = null;
resetButtonCount();
for (int res : functionResources) {
for (int res : functionResources)
{
addFunction(res);
}
@ -161,7 +161,8 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
findViewById(R.id.layoutButtons).setVisibility(View.VISIBLE);
}
public void setupFunctions(StandardFunctionInterface functionInterface, AssetDefinitionService assetSvs, Token token, NonFungibleAdapterInterface adp, List<BigInteger> tokenIds) {
public void setupFunctions(StandardFunctionInterface functionInterface, AssetDefinitionService assetSvs, Token token, NonFungibleAdapterInterface adp, List<BigInteger> tokenIds)
{
callStandardFunctions = functionInterface;
adapter = adp;
selection = tokenIds;
@ -173,10 +174,12 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
/**
* Use only for TokenScript function list
*
* @param functionInterface
* @param functionName function
* @param functionName function
*/
public void setupFunctionList(StandardFunctionInterface functionInterface, String functionName) {
public void setupFunctionList(StandardFunctionInterface functionInterface, String functionName)
{
callStandardFunctions = functionInterface;
if (functions == null) functions = new HashMap<>();
functions.clear();
@ -194,9 +197,13 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
*
* @param token
*/
private void addStandardTokenFunctions(Token token) {
private void addStandardTokenFunctions(Token token)
{
if (token == null) return;
for (Integer i : token.getStandardFunctions()) { addFunction(i); }
for (Integer i : token.getStandardFunctions())
{
addFunction(i);
}
}
public void revealButtons()
@ -204,18 +211,19 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
showButtons = true;
}
@Override
public void onClick(View v) {
if (v instanceof Button) { // Instance of 'primary' & 'secondary' buttons
Button button = (Button)v;
debounceButton(button);
handleAction(new ItemClick(button.getText().toString(), v.getId()));
} else if (v instanceof ImageButton) { // Instance of 'menu' button
bottomSheet.show();
}
private void onMainButtonClick(MaterialButton v)
{
debounceButton(v);
handleAction(new ItemClick(v.getText().toString(), v.getId()));
}
private void handleAction(ItemClick action) {
private void onMoreButtonClick()
{
bottomSheet.show();
}
private void handleAction(ItemClick action)
{
if (functions != null && functions.containsKey(action.buttonText))
{
handleUseClick(action);
@ -224,7 +232,8 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
{
buyFunctionInterface.handleBuyFunction(token);
}
else if (action.buttonId == R.string.generate_payment_request) {
else if (action.buttonId == R.string.generate_payment_request)
{
buyFunctionInterface.handleGeneratePaymentRequest(token);
}
else
@ -233,10 +242,12 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
}
}
private void handleStandardFunctionClick(ItemClick action) {
private void handleStandardFunctionClick(ItemClick action)
{
if (action.buttonId == R.string.action_sell)
{
if (isSelectionValid(action.buttonId)) callStandardFunctions.sellTicketRouter(selection);
if (isSelectionValid(action.buttonId))
callStandardFunctions.sellTicketRouter(selection);
}
else if (action.buttonId == R.string.action_send)
{
@ -248,11 +259,13 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
}
else if (action.buttonId == R.string.action_transfer)
{
if (isSelectionValid(action.buttonId)) callStandardFunctions.showTransferToken(selection);
if (isSelectionValid(action.buttonId))
callStandardFunctions.showTransferToken(selection);
}
else if (action.buttonId == R.string.action_use)
{
if (isSelectionValid(action.buttonId)) callStandardFunctions.selectRedeemTokens(selection);
if (isSelectionValid(action.buttonId))
callStandardFunctions.selectRedeemTokens(selection);
}
else
{
@ -260,8 +273,10 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
}
}
private void handleUseClick(ItemClick function) {
if (functions != null && functions.containsKey(function.buttonText)) {
private void handleUseClick(ItemClick function)
{
if (functions != null && functions.containsKey(function.buttonText))
{
TSAction action = functions.get(function.buttonText);
//first check for availability
if (!TextUtils.isEmpty(action.exclude))
@ -275,9 +290,12 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
}
//ensure we have sufficient tokens for selection
if (!hasCorrectTokens(action)) {
if (!hasCorrectTokens(action))
{
callStandardFunctions.displayTokenSelectionError(action);
} else {
}
else
{
List<BigInteger> selected = selection;
if (adapter != null) selected = adapter.getSelectedTokenIds(selection);
callStandardFunctions.handleTokenScriptFunction(function.buttonText, selected);
@ -285,31 +303,37 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
}
}
private boolean isSelectionValid(int buttonId) {
private boolean isSelectionValid(int buttonId)
{
List<BigInteger> selected = selection;
if (adapter != null) selected = adapter.getSelectedTokenIds(selection);
if (token == null || token.checkSelectionValidity(selected)) {
if (token == null || token.checkSelectionValidity(selected))
{
return true;
}
else {
else
{
displayInvalidSelectionError();
flashButton(findViewById(buttonId));
return false;
}
}
private boolean hasCorrectTokens(TSAction action) {
private boolean hasCorrectTokens(TSAction action)
{
//get selected tokens
if (adapter == null)
{
if (action.function != null) return action.function.getTokenRequirement() <= 1; //can't use multi-token with no selection adapter.
if (action.function != null)
return action.function.getTokenRequirement() <= 1; //can't use multi-token with no selection adapter.
else return true;
}
List<BigInteger> selected = adapter.getSelectedTokenIds(selection);
int groupings = adapter.getSelectedGroups();
if (action.function != null) {
if (action.function != null)
{
int requiredCount = action.function.getTokenRequirement();
if (requiredCount == 1 && selected.size() > 1 && groupings == 1) {
if (requiredCount == 1 && selected.size() > 1 && groupings == 1)
{
BigInteger first = getSelectedTokenId(selected);
selected.clear();
selected.add(first);
@ -321,45 +345,56 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
}
@Override
public void onTokenClick(View view, Token token, List<BigInteger> tokenIds, boolean selected) {
public void onTokenClick(View view, Token token, List<BigInteger> tokenIds, boolean selected)
{
int maxSelect = 1;
if (!selected && tokenIds.containsAll(selection)) {
if (!selected && tokenIds.containsAll(selection))
{
selection = new ArrayList<>();
}
if (!selected) return;
if (functions != null) {
if (functions != null)
{
//Wait for availability to complete
waitForMapBuild();
populateButtons(token, getSelectedTokenId(tokenIds));
for (TSAction action : functions.values()) {
if (action.function != null && action.function.getTokenRequirement() > maxSelect) {
for (TSAction action : functions.values())
{
if (action.function != null && action.function.getTokenRequirement() > maxSelect)
{
maxSelect = action.function.getTokenRequirement();
}
}
}
if (maxSelect <= 1) {
if (maxSelect <= 1)
{
selection = tokenIds;
if (adapter != null) adapter.setRadioButtons(true);
}
}
@Override
public void onLongTokenClick(View view, Token token, List<BigInteger> tokenIds) {
public void onLongTokenClick(View view, Token token, List<BigInteger> tokenIds)
{
//show radio buttons of all token groups
if (adapter != null) adapter.setRadioButtons(true);
selection = tokenIds;
Vibrator vb = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (vb != null && vb.hasVibrator()) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
if (vb != null && vb.hasVibrator())
{
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
VibrationEffect vibe = VibrationEffect.createOneShot(200, DEFAULT_AMPLITUDE);
vb.vibrate(vibe);
} else {
}
else
{
//noinspection deprecation
vb.vibrate(200);
}
@ -382,8 +417,7 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
{
functionMapComplete.acquire();
functionMapComplete.release();
}
catch (InterruptedException e)
} catch (InterruptedException e)
{
Timber.e(e);
functionMapComplete.release();
@ -392,50 +426,64 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
}
}
private void displayInvalidSelectionError() {
private void displayInvalidSelectionError()
{
Toast.makeText(getContext(), "Invalid token selection", Toast.LENGTH_SHORT).show();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
bottomSheet.dismiss();
ItemClick action = moreActionsAdapter.getItem(position);
handleAction(action);
}
public void setPrimaryButtonText(Integer resource) {
if (resource != null) {
public void setPrimaryButtonText(Integer resource)
{
if (resource != null)
{
primaryButtonWrapper.setVisibility(View.VISIBLE);
primaryButton.setText(resource);
} else {
}
else
{
primaryButtonWrapper.setVisibility(View.GONE);
}
}
public void setSecondaryButtonText(Integer resource) {
if (resource != null) {
public void setSecondaryButtonText(Integer resource)
{
if (resource != null)
{
secondaryButton.setVisibility(View.VISIBLE);
secondaryButton.setText(resource);
} else {
}
else
{
secondaryButton.setVisibility(View.GONE);
}
}
public void setPrimaryButtonEnabled(boolean enabled) {
public void setPrimaryButtonEnabled(boolean enabled)
{
primaryButton.setEnabled(enabled);
if (enabled) primaryButtonSpinner.setVisibility(View.GONE);
}
public void setPrimaryButtonWaiting() {
public void setPrimaryButtonWaiting()
{
primaryButton.setEnabled(false);
primaryButtonSpinner.setVisibility(View.VISIBLE);
}
public void setSecondaryButtonEnabled(boolean enabled) {
public void setSecondaryButtonEnabled(boolean enabled)
{
secondaryButton.setEnabled(enabled);
}
public void setPrimaryButtonClickListener(OnClickListener listener) {
public void setPrimaryButtonClickListener(OnClickListener listener)
{
primaryButton.setOnClickListener(listener);
}
@ -449,58 +497,44 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
}, 500);
}
/**
* Indicate token input error
*
* @param button
*/
private void flashButton(final Button button)
private void addFunction(ItemClick function)
{
if (button == null) return;
button.setBackgroundResource(R.drawable.button_round_error);
handler.postDelayed(() -> {
if (button.hashCode() == primaryButton.hashCode())
{
button.setBackgroundResource(R.drawable.selector_round_button);
}
else if (button.hashCode() == secondaryButton.hashCode())
switch (buttonCount)
{
case 0:
{
button.setBackgroundResource(R.drawable.selector_round_button_secondary);
}
}, 500);
}
private void addFunction(ItemClick function) {
switch (buttonCount) {
case 0: {
primaryButton.setText(function.buttonText);
primaryButton.setId(function.buttonId);
primaryButtonWrapper.setVisibility(View.VISIBLE);
primaryButton.setOnClickListener(this);
primaryButton.setOnClickListener(v -> onMainButtonClick(primaryButton));
break;
}
case 1: {
case 1:
{
secondaryButton.setText(function.buttonText);
secondaryButton.setId(function.buttonId);
secondaryButton.setVisibility(View.VISIBLE);
secondaryButton.setOnClickListener(this);
secondaryButton.setOnClickListener(v -> onMainButtonClick(secondaryButton));
break;
}
default: {
default:
{
moreActionsList.add(function);
moreActionsAdapter.notifyDataSetChanged();
moreButton.setVisibility(View.VISIBLE);
moreButton.setOnClickListener(this);
moreButton.setOnClickListener(v -> onMoreButtonClick());
}
}
buttonCount++;
}
private void addFunction(String function) {
private void addFunction(String function)
{
addFunction(new ItemClick(function, 0));
}
private void addFunction(int resourceId) {
private void addFunction(int resourceId)
{
addFunction(new ItemClick(context.getString(resourceId), resourceId));
}
@ -509,22 +543,6 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
walletType = type;
}
private static class FunctionItemAdapter extends ArrayAdapter<ItemClick>
{
public FunctionItemAdapter(Context context, int resource, List<ItemClick> objects) {
super(context, resource, 0, objects);
}
@SuppressLint("ViewHolder") @NotNull @Override
public View getView(int position, View convertView, @NotNull ViewGroup parent) {
ItemClick item = getItem(position);
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_action, parent, false);
((TextView)convertView.findViewById(android.R.id.text1)).setText(item.buttonText);
return convertView;
}
}
private void populateButtons(Token token, BigInteger tokenId)
{
if (token == null) return;
@ -586,7 +604,8 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
if (availableFunctions != null && availableFunctions.size() > 0)
{
SparseArray<String> actions = new SparseArray<>();
for (String actionName : availableFunctions.keySet()) actions.put(availableFunctions.get(actionName).order, actionName);
for (String actionName : availableFunctions.keySet())
actions.put(availableFunctions.get(actionName).order, actionName);
for (int i = 0; i < actions.size(); i++)
{
@ -600,7 +619,8 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
*/
private boolean setupCustomTokenActions()
{
if (token.tokenInfo.chainId == MATIC_ID && token.isNonFungible()) {
if (token.tokenInfo.chainId == MATIC_ID && token.isNonFungible())
{
return false;
}
@ -643,8 +663,7 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
try
{
functionMapComplete.acquire();
}
catch (InterruptedException e)
} catch (InterruptedException e)
{
Timber.e(e);
}
@ -716,7 +735,26 @@ public class FunctionButtonBar extends LinearLayout implements AdapterView.OnIte
private void addPurchaseVerb(Token token, OnRampRepositoryType onRampRepository)
{
OnRampContract contract = onRampRepository.getContract(token);
String symbol = contract.getSymbol().isEmpty()? context.getString(R.string.crypto) : token.tokenInfo.symbol;
String symbol = contract.getSymbol().isEmpty() ? context.getString(R.string.crypto) : token.tokenInfo.symbol;
addFunction(new ItemClick(context.getString(R.string.action_buy_crypto, symbol), R.string.action_buy_crypto));
}
private static class FunctionItemAdapter extends ArrayAdapter<ItemClick> {
public FunctionItemAdapter(Context context, int resource, List<ItemClick> objects)
{
super(context, resource, 0, objects);
}
@SuppressLint("ViewHolder")
@NotNull
@Override
public View getView(int position, View convertView, @NotNull ViewGroup parent)
{
ItemClick item = getItem(position);
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_action, parent, false);
((TextView) convertView.findViewById(android.R.id.text1)).setText(item.buttonText);
return convertView;
}
}
}

@ -1,144 +0,0 @@
package com.alphawallet.app.widget;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import com.google.android.material.textfield.TextInputLayout;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewPropertyAnimatorListenerAdapter;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.EditText;
import android.widget.TextView;
import com.alphawallet.app.R;
/**
* TextInputLayout temporary workaround for helper text showing
* https://gist.github.com/drstranges/1a86965f582f610244d6
*/
public class HelperTextInputLayout extends TextInputLayout {
static final Interpolator FAST_OUT_SLOW_IN_INTERPOLATOR = new FastOutSlowInInterpolator();
private CharSequence mHelperText;
private ColorStateList mHelperTextColor;
private boolean mHelperTextEnabled = false;
private boolean mErrorEnabled = false;
private TextView mHelperView;
private int mHelperTextAppearance = R.style.HelperTextAppearance;
public HelperTextInputLayout(Context _context) {
super(_context);
}
public HelperTextInputLayout(Context _context, AttributeSet _attrs) {
super(_context, _attrs);
final TypedArray a = getContext().obtainStyledAttributes(
_attrs,
R.styleable.HelperTextInputLayout,0,0);
try {
mHelperTextColor = a.getColorStateList(R.styleable.HelperTextInputLayout_helperTextColor);
mHelperText = a.getText(R.styleable.HelperTextInputLayout_helperText);
} finally {
a.recycle();
}
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
super.addView(child, index, params);
if (child instanceof EditText) {
if (!TextUtils.isEmpty(mHelperText)) {
setHelperText(mHelperText);
}
}
}
public int getHelperTextAppearance() {
return mHelperTextAppearance;
}
public void setHelperTextAppearance(int _helperTextAppearanceResId) {
mHelperTextAppearance = _helperTextAppearanceResId;
}
public void setHelperTextColor(ColorStateList _helperTextColor) {
mHelperTextColor = _helperTextColor;
}
public void setHelperTextEnabled(boolean _enabled) {
if (mHelperTextEnabled == _enabled) return;
if (_enabled && mErrorEnabled) {
setErrorEnabled(false);
}
if (this.mHelperTextEnabled != _enabled) {
if (_enabled) {
this.mHelperView = new TextView(this.getContext());
this.mHelperView.setTextAppearance(this.getContext(), this.mHelperTextAppearance);
if (mHelperTextColor != null){
this.mHelperView.setTextColor(mHelperTextColor);
}
this.mHelperView.setVisibility(INVISIBLE);
this.addView(this.mHelperView);
} else {
this.removeView(this.mHelperView);
this.mHelperView = null;
}
this.mHelperTextEnabled = _enabled;
}
}
public void setHelperText(CharSequence _helperText) {
mHelperText = _helperText;
if (!this.mHelperTextEnabled) {
if (TextUtils.isEmpty(mHelperText)) {
return;
}
this.setHelperTextEnabled(true);
}
if (!TextUtils.isEmpty(mHelperText)) {
this.mHelperView.setText(mHelperText);
this.mHelperView.setVisibility(VISIBLE);
ViewCompat.setAlpha(this.mHelperView, 0.0F);
ViewCompat.animate(this.mHelperView)
.alpha(1.0F).setDuration(200L)
.setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR)
.setListener(null).start();
} else if (this.mHelperView.getVisibility() == VISIBLE) {
ViewCompat.animate(this.mHelperView)
.alpha(0.0F).setDuration(200L)
.setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR)
.setListener(new ViewPropertyAnimatorListenerAdapter() {
public void onAnimationEnd(View view) {
mHelperView.setText(null);
mHelperView.setVisibility(INVISIBLE);
}
}).start();
}
this.sendAccessibilityEvent(2048);
}
@Override
public void setErrorEnabled(boolean _enabled) {
if (mErrorEnabled == _enabled) return;
mErrorEnabled = _enabled;
if (_enabled && mHelperTextEnabled) {
setHelperTextEnabled(false);
}
super.setErrorEnabled(_enabled);
if (!(_enabled || TextUtils.isEmpty(mHelperText))) {
setHelperText(mHelperText);
}
}
}

@ -286,16 +286,16 @@ public class InputAddress extends RelativeLayout implements ItemClickListener, E
{
case ERROR:
boxLayout.setBackgroundResource(R.drawable.background_input_error);
labelText.setTextColor(context.getColor(R.color.danger));
labelText.setTextColor(context.getColor(R.color.error));
break;
case UNSELECTED:
boxLayout.setBackgroundResource(R.drawable.background_password_entry);
labelText.setTextColor(context.getColor(R.color.dove));
labelText.setTextColor(context.getColor(R.color.text_secondary));
errorText.setVisibility(View.GONE);
break;
case SELECTED:
boxLayout.setBackgroundResource(R.drawable.background_input_selected);
labelText.setTextColor(context.getColor(R.color.azure));
labelText.setTextColor(context.getColor(R.color.brand));
errorText.setVisibility(View.GONE);
break;
}

@ -56,7 +56,7 @@ public class InputAmount extends LinearLayout
private final NumericInput editText;
private final TextView symbolText;
private final TokenIcon icon;
private final ChainName chainName;
private final StandardHeader header;
private final TextView availableSymbol;
private final TextView availableAmount;
private final TextView allFunds;
@ -87,7 +87,7 @@ public class InputAmount extends LinearLayout
editText = findViewById(R.id.amount_entry);
symbolText = findViewById(R.id.text_token_symbol);
icon = findViewById(R.id.token_icon);
chainName = findViewById(R.id.chain_name);
header = findViewById(R.id.header);
availableSymbol = findViewById(R.id.text_symbol);
availableAmount = findViewById(R.id.text_available);
allFunds = findViewById(R.id.text_all_funds);
@ -116,7 +116,7 @@ public class InputAmount extends LinearLayout
this.assetService = assetDefinitionService;
this.amountReadyCallback = amountCallback;
icon.bindData(token, assetService);
chainName.setChainID(token.tokenInfo.chainId);
header.getChainName().setChainID(token.tokenInfo.chainId);
updateAvailableBalance();
this.realm = tokensService.getWalletRealmInstance();
@ -186,12 +186,12 @@ public class InputAmount extends LinearLayout
if (showError)
{
errorText.setVisibility(View.VISIBLE);
editText.setTextColor(context.getColor(R.color.danger));
editText.setTextColor(context.getColor(R.color.error));
}
else
{
errorText.setVisibility(View.GONE);
editText.setTextColor(context.getColor(R.color.text_dark_gray));
editText.setTextColor(context.getColor(R.color.text_secondary));
}
}
@ -462,11 +462,10 @@ public class InputAmount extends LinearLayout
boolean showChainName = a.getBoolean(R.styleable.InputView_showChainName, true);
boolean currencyMode = a.getBoolean(R.styleable.InputView_currencyMode, false);
int headerTextId = a.getResourceId(R.styleable.InputView_label, R.string.amount);
findViewById(R.id.layout_header_amount).setVisibility(showHeader ? View.VISIBLE : View.GONE);
header.setVisibility(showHeader ? View.VISIBLE : View.GONE);
allFunds.setVisibility(showAllFunds ? View.VISIBLE : View.GONE);
TextView headerText = findViewById(R.id.text_header);
headerText.setText(headerTextId);
chainName.setVisibility(showChainName ? View.VISIBLE : View.GONE);
header.setText(headerTextId);
header.getChainName().setVisibility(showChainName ? View.VISIBLE : View.GONE);
if (currencyMode)
{
symbolText.setText(TickerService.getCurrencySymbolTxt());

@ -8,7 +8,6 @@ import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.alphawallet.app.R;
@ -21,14 +20,13 @@ import com.alphawallet.app.ui.widget.entity.NumericInput;
public class InputFiatView extends LinearLayout {
private final Context context;
private final NumericInput amountInput;
private final RelativeLayout headerLayout;
private final TextView headerText;
private final LinearLayout moreLayout;
private final ImageView icon;
private final ImageView expandMore;
private final TextView symbolText;
private final TextView subTextLabel;
private final TextView subTextValue;
private final StandardHeader header;
private InputFiatCallback callback;
public InputFiatView(Context context, AttributeSet attrs)
@ -37,8 +35,7 @@ public class InputFiatView extends LinearLayout {
this.context = context;
inflate(context, R.layout.item_input_fiat, this);
headerLayout = findViewById(R.id.layout_header_amount);
headerText = findViewById(R.id.text_header);
header = findViewById(R.id.header);
moreLayout = findViewById(R.id.layout_more_click);
expandMore = findViewById(R.id.expand_more);
icon = findViewById(R.id.icon);
@ -74,8 +71,8 @@ public class InputFiatView extends LinearLayout {
{
boolean showHeader = a.getBoolean(R.styleable.InputView_show_header, true);
int headerTextId = a.getResourceId(R.styleable.InputView_label, R.string.enter_target_price);
headerText.setText(headerTextId);
headerLayout.setVisibility(showHeader ? View.VISIBLE : View.GONE);
header.setText(headerTextId);
header.setVisibility(showHeader ? View.VISIBLE : View.GONE);
boolean canChangeCurrency = a.getBoolean(R.styleable.InputView_can_change_currency, true);
expandMore.setVisibility(canChangeCurrency ? VISIBLE : GONE);
@ -123,11 +120,13 @@ public class InputFiatView extends LinearLayout {
symbolText.setText(symbol);
}
public void showKeyboard() {
public void showKeyboard()
{
amountInput.requestFocus();
}
public void setSubTextValue(String text) {
public void setSubTextValue(String text)
{
subTextValue.setText(text);
}
}

@ -38,6 +38,7 @@ public class InputView extends LinearLayout {
private final EditText editText;
private final RelativeLayout boxLayout;
private final ImageButton scanQrIcon;
private final StandardHeader header;
private int labelResId;
private int lines;
@ -57,6 +58,7 @@ public class InputView extends LinearLayout {
boxLayout = findViewById(R.id.box_layout);
scanQrIcon = findViewById(R.id.img_scan_qr);
pasteItem = findViewById(R.id.text_paste);
header = findViewById(R.id.layout_header);
getAttrs(context, attrs);
@ -103,9 +105,8 @@ public class InputView extends LinearLayout {
boolean showHeader = a.getBoolean(R.styleable.InputView_show_header, false);
boolean showPaste = a.getBoolean(R.styleable.InputView_show_paste, false);
int headerTextId = a.getResourceId(R.styleable.InputView_label, R.string.token_name);
findViewById(R.id.layout_header).setVisibility(showHeader ? View.VISIBLE : View.GONE);
TextView headerText = findViewById(R.id.text_header);
headerText.setText(headerTextId);
header.setVisibility(showHeader ? View.VISIBLE : View.GONE);
header.setText(headerTextId);
scanQrIcon.setVisibility(noCam ? View.GONE : View.VISIBLE);
pasteItem.setVisibility(showPaste ? View.VISIBLE : View.GONE);
@ -222,16 +223,16 @@ public class InputView extends LinearLayout {
{
case ERROR:
boxLayout.setBackgroundResource(R.drawable.background_input_error);
labelText.setTextColor(context.getColor(R.color.danger));
labelText.setTextColor(context.getColor(R.color.error));
break;
case UNSELECTED:
boxLayout.setBackgroundResource(R.drawable.background_password_entry);
labelText.setTextColor(context.getColor(R.color.dove));
labelText.setTextColor(context.getColor(R.color.text_secondary));
errorText.setVisibility(View.GONE);
break;
case SELECTED:
boxLayout.setBackgroundResource(R.drawable.background_input_selected);
labelText.setTextColor(context.getColor(R.color.azure));
labelText.setTextColor(context.getColor(R.color.brand));
errorText.setVisibility(View.GONE);
break;
}

@ -50,6 +50,7 @@ public class NFTImageView extends RelativeLayout {
private final ProgressBar progressBar;
private final Handler handler = new Handler(Looper.getMainLooper());
private Request loadRequest;
/**
* Prevent glide dumping log errors - it is expected that load will fail
*/

@ -11,9 +11,10 @@ import android.widget.RelativeLayout;
import android.widget.TextView;
import com.alphawallet.app.R;
import com.google.android.material.card.MaterialCardView;
public class NotificationView extends LinearLayout {
private RelativeLayout layout;
private MaterialCardView layout;
private TextView title;
private TextView message;
private Button primaryButton;
@ -198,7 +199,7 @@ public class NotificationView extends LinearLayout {
}
public void setNotificationBackgroundColor(int backgroundColorRes) {
layout.setBackgroundTintList(ContextCompat.getColorStateList(getContext(), backgroundColorRes));
layout.setCardBackgroundColor(backgroundColorRes);
}
public void setNotificationTextColor(int textColorRes) {

@ -208,12 +208,12 @@ public class PasswordInputView extends LinearLayout implements TextView.OnEditor
error.setText(resId);
error.setVisibility(View.GONE);
editText.setBackgroundResource(R.drawable.background_password_entry);
label.setTextColor(ContextCompat.getColor(getContext(), R.color.silver));
label.setTextColor(ContextCompat.getColor(getContext(), R.color.text_secondary));
} else {
error.setText(resId);
error.setVisibility(View.VISIBLE);
editText.setBackgroundResource(R.drawable.background_password_error);
label.setTextColor(ContextCompat.getColor(getContext(), R.color.warning_red));
label.setTextColor(ContextCompat.getColor(getContext(), R.color.error));
}
}
@ -231,17 +231,17 @@ public class PasswordInputView extends LinearLayout implements TextView.OnEditor
if (message == null) {
error.setVisibility(View.GONE);
editText.setBackgroundResource(R.drawable.background_password_entry);
label.setTextColor(ContextCompat.getColor(getContext(), R.color.silver));
label.setTextColor(ContextCompat.getColor(getContext(), R.color.text_secondary));
} else if (message.toString().isEmpty()) {
error.setText(message);
error.setVisibility(View.GONE);
editText.setBackgroundResource(R.drawable.background_password_entry);
label.setTextColor(ContextCompat.getColor(getContext(), R.color.silver));
label.setTextColor(ContextCompat.getColor(getContext(), R.color.text_secondary));
} else {
error.setText(message);
error.setVisibility(View.VISIBLE);
editText.setBackgroundResource(R.drawable.background_password_error);
label.setTextColor(ContextCompat.getColor(getContext(), R.color.warning_red));
label.setTextColor(ContextCompat.getColor(getContext(), R.color.error));
}
}

@ -92,7 +92,7 @@ public class ProgressView extends RelativeLayout {
public void setWhiteCircle()
{
int colour = ContextCompat.getColor(context, R.color.white);
int colour = ContextCompat.getColor(context, R.color.surface);
setTint(colour, false);
}

@ -1,92 +0,0 @@
package com.alphawallet.app.widget;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.alphawallet.app.R;
import java.util.Locale;
public class SearchDialog extends Dialog {
private final Spinner spinnerMatch;
private final Spinner spinnerClass;
private final Spinner spinnerSeats;
private final Spinner spinnerDate;
private final SeekBar priceSeekBar;
private final Button btnApply;
private final TextView seekBarValue;
public SearchDialog(Activity activity) {
super(activity);
setupDialog();
spinnerMatch = findViewById(R.id.spinner_match);
spinnerMatch.setAdapter(createAdapter(activity, R.array.filter_match));
spinnerClass = findViewById(R.id.spinner_class);
spinnerClass.setAdapter(createAdapter(activity, R.array.filter_class));
spinnerSeats = findViewById(R.id.spinner_seats);
spinnerSeats.setAdapter(createAdapter(activity, R.array.filter_seats));
spinnerDate = findViewById(R.id.spinner_date);
spinnerDate.setAdapter(createAdapter(activity, R.array.filter_search_date));
btnApply = findViewById(R.id.btn_filter);
btnApply.setOnClickListener(v -> {
search();
dismiss();
});
seekBarValue = findViewById(R.id.seek_bar_value);
priceSeekBar = findViewById(R.id.seek_bar_price);
priceSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
double value = progress * 100.00;
String val = String.format(Locale.getDefault(),"$%.2f", value);
seekBarValue.setText(val);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
private void setupDialog() {
setContentView(R.layout.dialog_search);
setCanceledOnTouchOutside(true);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
setCanceledOnTouchOutside(true);
getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
private void search() {
//TODO: Search action
}
private ArrayAdapter<CharSequence> createAdapter(Activity activity, int resId) {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(activity, resId, R.layout.item_spinner);
adapter.setDropDownViewResource(R.layout.item_spinner_dropdown);
return adapter;
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save