我正在尝试Global Variable
为我的整个app
. 但似乎它不起作用。
我已经按照指南制作了一个Global Variable
. 这是我到目前为止所拥有的:
GolobalVariables appState;
appState = ((GolobalVariables) this.getApplication());
这是我on touch event
的工作:
@Override
public void onLongPress(MotionEvent e) {
mScrollView.post(new Runnable() {
@Override
public void run() {
darkMode();
appState.setDarkModeOn(!appState.isDarkModeOn());
}
});
}
这是darkMode method
:
private void darkMode() {
Log.d("DarkMode", "`" + appState.isDarkModeOn());
if(appState.isDarkModeOn()) {
maarivRelativeLayout.setBackgroundColor(Color.parseColor("#333333"));
for (int i = 0; i < maarivLinearLayout.getChildCount(); i++) {
((TextView) maarivLinearLayout.getChildAt(i)).setTextColor(Color.parseColor("#FFFFFF"));
}
} else {
maarivRelativeLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));
for (int i = 0; i < maarivLinearLayout.getChildCount(); i++) {
((TextView) maarivLinearLayout.getChildAt(i)).setTextColor(Color.parseColor("#333333"));
}
}
}
我更改了状态,boolean
以便在切换活动时变量保持不变。只有当用户长按屏幕时,才会切换。
出现2个问题:
- 它的布尔值不会在整个应用程序中保持其状态。
当关闭和重新打开同一个活动时,日志语句会在打开时显示为假,在长按时再次显示为假。真实和真实。
这是我的清单
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Davening"/> <activity android:name=".Benching"/> <activity android:name=".Zmanim"/> <activity android:name=".Extras"></activity> <activity android:name=".Shacharis"></activity> <activity android:name=".Mincha"></activity> <activity android:name=".Maariv"></activity> <activity android:name=".Compass"></activity> <activity android:name=".TestingZone"></activity> <!--Camera--> <activity android:name=".CameraView" android:label="@string/app_name" android:screenOrientation="portrait"> <!-- configure this activity to use landscape orientation --> </activity> <!--<application android:theme="@style/Theme.AppCompat.Light.NoActionBar" />--> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.CAMERA"/> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera2" /> <uses-feature android:name="android.hardware.camera.autofocus" /><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
应用索引。有关更多信息,请参阅https://g.co/AppIndexing/AndroidStudio。-->
这是我的全局变量类:
package com.example.edonfreiner.siddur;
import android.app.Application;
public class GolobalVariables extends Application{
public boolean darkModeOn = false;
public boolean isDarkModeOn() {
return darkModeOn;
}
public void setDarkModeOn(boolean darkModeOn) {
this.darkModeOn = darkModeOn;
}
}