夜間モード切り替え
7711 ワード
button実装モードの切り替えレイアウトのコードをクリック
パッケージされたキットコード
//ツールパッケージのヘルプメインクラスで呼び出すとモードの切り替えが実現します.あまり言わないでください.次にメインクラスのコードを示します.
もちろんこれらはまだ足りません.私たちのモード切り替えはテーマの呼び出しです.次は私たちの昼と夜のテーマモードです.
上のコードだけで私たちが必要とするモードの切り替えを実現することができます.必要なあなたは早く行動しましょう.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" >
<Button android:id="@+id/changemode" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text=" " />
</RelativeLayout>
パッケージされたキットコード
import android.content.Context;
import android.content.SharedPreferences;
public class SPUtils {
private static SharedPreferences sp;
public static void put(Context ct, String key, String value) {
if (sp == null)
sp = ct.getSharedPreferences(key, 0);
sp.edit().putString(key, value).commit();
}
public static String get(Context ct, String key,String value) {
if (sp == null)
sp = ct.getSharedPreferences(key, 0);
if (sp.getString(key, "") != null) {
return sp.getString(key, "");
}
return null;
}
}
//ツールパッケージのヘルプメインクラスで呼び出すとモードの切り替えが実現します.あまり言わないでください.次にメインクラスのコードを示します.
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button changemode;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (SPUtils.get(this, "theme", "dayTheme").equals("dayTheme")) {
setTheme(R.style.dayTheme);
} else {
setTheme(R.style.nightTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
changemode=(Button) findViewById(R.id.changemode);
changemode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (SPUtils.get(MainActivity.this, "theme", "dayTheme").equals(
"dayTheme")) {
SPUtils.put(MainActivity.this, "theme", "nightTheme");
} else {
SPUtils.put(MainActivity.this, "theme", "dayTheme");
}
recreate();
}
});
}
}
もちろんこれらはまだ足りません.私たちのモード切り替えはテーマの呼び出しです.次は私たちの昼と夜のテーマモードです.
<!-- -->
<style name="dayTheme" parent="AppTheme"> <item name="android:textColor">#525252</item> <item name="android:background">#f7f7f7</item> </style>
<!-- -->
<style name="nightTheme" parent="AppTheme"> <item name="android:textColor">#868a96</item> <item name="android:background">#1e1e2a </item> </style>
上のコードだけで私たちが必要とするモードの切り替えを実現することができます.必要なあなたは早く行動しましょう.