首页 > 解决方案 > 如何使用菜单中的单选按钮更改文本视图的文本和背景颜色

问题描述

基本上,我正在尝试在单击单选按钮时在黑色背景上创建白色文本的夜间模式。我希望单选按钮在未单击时为灰色,在单击/活动时为绿色。我已经能够在点击时使项目吐司,但从这里丢失了。我在下面附上了截图。不知道下一步该做什么。谢谢你的帮助。

夜间模式灰度图像

活动中的代码

enter code here @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_text, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement

        if (id == R.id.item2) {
            Toast.makeText(this, "Night mode", Toast.LENGTH_LONG).show();
            return true;
        }

        if (id == R.id.item3) {
            Toast.makeText(this, "Fonts", Toast.LENGTH_LONG).show();
            return true;
        }

        if (id == R.id.font1) {
            Toast.makeText(this, "Font 1", Toast.LENGTH_LONG).show();
            return true;
        }

        if (id == R.id.font2) {
            Toast.makeText(this, "Font 2", Toast.LENGTH_LONG).show();
            return true;
        }

        if (id == R.id.font3) {
            Toast.makeText(this, "Font 3", Toast.LENGTH_LONG).show();
            return true;
        }


        return super.onOptionsItemSelected(item);
    }
}


Menu xml


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:title="@string/settings"
        app:showAsAction="always">

        <menu>

            <item android:id="@+id/item2"
                android:title="@string/night_mode"
                android:icon="@drawable/ic_night"
                app:showAsAction="withText" />

            <item android:id="@+id/item3"
                android:title="@string/font"
                app:showAsAction="never" >

                <menu>

                    <item android:id="@+id/font1"
                        android:title="Times Roman"/>

                    <item android:id="@+id/font2"
                        android:title="Vollkorn"/>

                    <item android:id="@+id/font3"
                        android:title="Default"/>

                </menu>

            </item>


        </menu>


    </item>


</menu>

标签: javaandroidandroid-studioradio-button

解决方案


您可以使用官方AppCompatDelegate.setDefaultNightMode(MODE),其中 MODE 代表以下场景之一:

  • AppCompatDelegate.MODE_NIGHT_YES
  • AppCompatDelegate.MODE_NIGHT_NO
  • AppCompatDelegate.MODE_NIGHT_AUTO

对于您的项目,您将需要在 和 之间切换MODE_NIGHT_NOMODE_NIGHT_YES因为MODE_NIGHT_AUTO会根据时间更改应用程序主题。

当您点击单选按钮时,您必须切换模式并重新创建活动,调用activity.recreate()

有关更多信息,这里有一篇有用的文章:DayNight Theme Android Tutorial with Example


推荐阅读