点击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>
就上面的代码 就能实现我们需要的模式的切换了 需要的你 快快行动起来吧!