android主题切换(简单的白/夜间模式的切换)、防止按钮的多次点击

效果图:

  

  

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="@color/viewBackground"
        android:gravity="center"
        android:text="跳转到Activity"
        android:textColor="@color/textColorPrimary" />

    <TextView
        android:id="@+id/tv2"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="10dp"
        android:background="@color/viewBackground"
        android:gravity="center"
        android:text="跳转到有Fragment的Activity"
        android:textColor="@color/textColorPrimary" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="夜间模式" />

        <Switch
            android:id="@+id/sw"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginTop="20dp" />
    </RelativeLayout>

</LinearLayout>

values/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#009688</color>
    <color name="colorPrimaryDark">#ffff8800</color>
    <color name="colorAccent">#009688</color>

    <color name="textColorPrimary">#ffff8800</color>
    <color name="viewBackground">#ffffff</color>
    <color name="colorDayNightChange">#ffff8800</color>

    <color name="transparent">#00000000</color>
</resources>

values-night/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#35464e</color>
    <color name="colorPrimaryDark">#303030</color>
    <color name="colorAccent">#ffffff</color>

    <color name="textColorPrimary">#ff0099cc</color>
    <color name="viewBackground">#A4A4A4</color>
    <color name="colorDayNightChange">#ff0099cc</color>
</resources>

java代码设置并保存状态:

突然发现9.0的系统其它页面不起作用(8.1的真机可以,9.0的模拟器本页面可以,其它页面不起作用),所以自定义一个BaseActivity,其它页面全部继承BaseActivity。

还有一点就是虚拟按键栏的背景色,因为我的虚拟按键一直是隐藏的,所以一直没发现。当我把虚拟按键调出来一看夜间模式下也是白色的,所以在BaseActivity中也设置了一下虚拟按键栏的背景色。

package com.shanjing.android_theme.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;

public class BaseActivity extends AppCompatActivity {

    SharedPreferences sprfMain;
    SharedPreferences.Editor editorMain;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sprfMain = getSharedPreferences("counter", Context.MODE_PRIVATE);
        editorMain = sprfMain.edit();
        //取出保存的值(取数据)
        boolean isChecked = sprfMain.getBoolean("isChecked", false);
        //根据保存的值设置主题状态
        if (isChecked) {
            getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
            //设置夜间模式下虚拟按键栏的背景色
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setNavigationBarColor(Color.parseColor("#303030"));
            }
        } else {
            getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
            //设置日间模式下虚拟按键栏的背景色
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setNavigationBarColor(Color.parseColor("#ffffff"));
            }
        }
    }
}
package com.shanjing.android_theme;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatDelegate;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import com.shanjing.android_theme.utils.ButtonUtils;

/**
 * 入口
 */
public class MainActivity extends BaseActivity {

    private Switch sw;
    private TextView tv, tv2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sw = findViewById(R.id.sw);
        tv = findViewById(R.id.tv);
        tv2 = findViewById(R.id.tv2);

        //取出保存的值(取数据)
        boolean isChecked = sprfMain.getBoolean("isChecked", false);
        sw.setChecked(isChecked);//获取状态并设置当前状态

        //开关
        sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                    //保存数据
                    editorMain.putBoolean("isChecked", true);
                    editorMain.commit();

                } else {
                    getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                    //保存数据
                    editorMain.putBoolean("isChecked", false);
                    editorMain.commit();
                }
            }
        });

        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ButtonUtils.isFastDoubleClick(R.id.tv)) {
                    startActivity(new Intent(MainActivity.this, TwoActivity.class));
                }
            }
        });

        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ButtonUtils.isFastDoubleClick(R.id.tv)) {
                    startActivity(new Intent(MainActivity.this, ThreeActivity.class));
                }
            }
        });

    }
}

按钮点击快的话会跳转页面两次,所以用了一个防止重复按钮的工具类:

package com.shanjing.android_theme.utils;

import android.util.Log;

/**
 * 防止按钮重复点击的工具类
 */
public class ButtonUtils {
    private static long lastClickTime = 0;
    private static long DIFF = 1000;
    private static int lastButtonId = -1;

    /**
     * 判断两次点击的间隔,如果小于1000,则认为是多次无效点击
     *
     * @return
     */
    public static boolean isFastDoubleClick() {
        return isFastDoubleClick(-1, DIFF);
    }

    /**
     * 判断两次点击的间隔,如果小于2000,则认为是多次无效点击
     *
     * @return
     */
    public static boolean isFastDoubleClick(int buttonId) {
        return isFastDoubleClick(buttonId, DIFF);
    }

    /**
     * 判断两次点击的间隔,如果小于diff,则认为是多次无效点击
     *
     * @param diff
     * @return
     */
    public static boolean isFastDoubleClick(int buttonId, long diff) {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (lastButtonId == buttonId && lastClickTime > 0 && timeD < diff) {
            Log.v("isFastDoubleClick", "短时间内按钮多次触发");
            return true;
        }
        lastClickTime = time;
        lastButtonId = buttonId;
        return false;
    }
}

用法:

 tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ButtonUtils.isFastDoubleClick(R.id.tv)) {
                    startActivity(new Intent(MainActivity.this, TwoActivity.class));
                }
            }
        });

Fragment所在页面的布局:

<?xml version="1.0" encoding="utf-8"?>
<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">

    <RadioGroup
        android:id="@+id/rg"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_alignParentBottom="true"
        android:background="@color/viewBackground"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/rb_home"
            style="@style/HR_TabRadioButton"
            android:drawableTop="@drawable/tab_hr_home_selector"
            android:text="首页" />

        <RadioButton
            android:id="@+id/rb_mall"
            style="@style/HR_TabRadioButton"
            android:drawableTop="@drawable/tab_hr_cart_selector"
            android:text="购物车" />

        <View style="@style/HR_TabRadioButton" />

        <RadioButton
            android:id="@+id/rb_video"
            style="@style/HR_TabRadioButton"
            android:drawableTop="@drawable/tab_hr_video_selector"
            android:text="视频" />

        <RadioButton
            android:id="@+id/rb_my"
            style="@style/HR_TabRadioButton"
            android:drawableTop="@drawable/tab_hr_my_selector"
            android:text="个人中心" />
    </RadioGroup>

    <LinearLayout
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/iv"
            android:layout_width="26dp"
            android:layout_height="26dp"
            android:background="@drawable/icon_publish_def" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/rg" />
</RelativeLayout>

主要代码:

此处8.1真机测试的没问题,9.0模拟器测试切换Fragment内容会重影,所以重写onSaveInstanceState进行解决。

package com.shanjing.android_theme;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.shanjing.android_theme.activity.IssueActivity;
import com.shanjing.android_theme.fragment.HRCartFragment;
import com.shanjing.android_theme.fragment.HRHomeFragment;
import com.shanjing.android_theme.fragment.HRMyFragment;
import com.shanjing.android_theme.fragment.HRVideoFragment;

public class ThreeActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    private RadioGroup rg;
    private RadioButton rb_home;
    private HRHomeFragment hrHomeFragment;
    private HRCartFragment hrCartFragment;
    private HRVideoFragment hrVideoFragment;
    private HRMyFragment hrMyFragment;
    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_three);
        initView();
    }

    private void initView() {
        rg = findViewById(R.id.rg);
        rb_home = findViewById(R.id.rb_home);
        iv = findViewById(R.id.iv);
        rg.setOnCheckedChangeListener(this);
        rb_home.setChecked(true);//设置首页选中
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ThreeActivity.this, IssueActivity.class));
            }
        });
    }

    private int mPosition;

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        mPosition = checkedId;

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideAllFragment(transaction);
        if (checkedId == R.id.rb_home) {
            if (hrHomeFragment == null) {
                hrHomeFragment = new HRHomeFragment();
                transaction.add(R.id.fragment_container, hrHomeFragment);
            } else {
                transaction.show(hrHomeFragment);
            }
        } else if (checkedId == R.id.rb_mall) {
            if (hrCartFragment == null) {
                hrCartFragment = new HRCartFragment();
                transaction.add(R.id.fragment_container, hrCartFragment);
            } else {
                transaction.show(hrCartFragment);
            }
        } else if (checkedId == R.id.rb_video) {
            if (hrVideoFragment == null) {
                hrVideoFragment = new HRVideoFragment();
                transaction.add(R.id.fragment_container, hrVideoFragment);
            } else {
                transaction.show(hrVideoFragment);
            }
        } else if (checkedId == R.id.rb_my) {
            if (hrMyFragment == null) {
                hrMyFragment = new HRMyFragment();
                transaction.add(R.id.fragment_container, hrMyFragment);
            } else {
                transaction.show(hrMyFragment);
            }
        }
        transaction.commit();
    }

    public void hideAllFragment(FragmentTransaction transaction) {
        if (hrHomeFragment != null) {
            transaction.hide(hrHomeFragment);
        }
        if (hrCartFragment != null) {
            transaction.hide(hrCartFragment);
        }
        if (hrVideoFragment != null) {
            transaction.hide(hrVideoFragment);
        }
        if (hrMyFragment != null) {
            transaction.hide(hrMyFragment);
        }
    }

    /**
     * 解决9.0Fragment的重影问题
     *
     * @param outState
     */
    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        /* 记录当前的position */
        outState.putInt("position", mPosition);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mPosition = savedInstanceState.getInt("position");
        onCheckedChanged(rg, mPosition);
    }

}

其它Fragment里面没有内容就不在贴出了,详细代码请猛戳一下链接:

GitHub地址:https://github.com/cuiwenju2017/Android_Theme

猜你喜欢

转载自blog.csdn.net/juer2017/article/details/100545041