java - 如何使用菜单中的单选按钮更改文本视图的文本和背景颜色
问题描述
基本上,我正在尝试在单击单选按钮时在黑色背景上创建白色文本的夜间模式。我希望单选按钮在未单击时为灰色,在单击/活动时为绿色。我已经能够在点击时使项目吐司,但从这里丢失了。我在下面附上了截图。不知道下一步该做什么。谢谢你的帮助。
活动中的代码
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>
解决方案
您可以使用官方AppCompatDelegate.setDefaultNightMode(MODE)
,其中 MODE 代表以下场景之一:
- AppCompatDelegate.MODE_NIGHT_YES
- AppCompatDelegate.MODE_NIGHT_NO
- AppCompatDelegate.MODE_NIGHT_AUTO
对于您的项目,您将需要在 和 之间切换MODE_NIGHT_NO
,MODE_NIGHT_YES
因为MODE_NIGHT_AUTO
会根据时间更改应用程序主题。
当您点击单选按钮时,您必须切换模式并重新创建活动,调用activity.recreate()
有关更多信息,这里有一篇有用的文章:DayNight Theme Android Tutorial with Example
推荐阅读
- python-imaging-library - 如何在 python 中将 PyPDF.PageObject 页面呈现为 PIL 图像?
- java - 从 ArrayList 中删除重复项?
- swift - 如何使用第一个函数作为第二个函数的闭包
- powershell - Chart.point 标签不适用于创建的 2 个图表而不是 1 个
- android - camera2:聚焦区域和焦距问题
- xunit - 如何将参数传递给通过控制台运行器运行的 xunit 单元测试?
- python-3.x - 不明白为什么这个 python 代码不起作用
- c++ - 指向同一个地址的空指针
- java - AudioInputStream 在 8 位 WAV 声音 Mac OSX 结束时弹出声音 [Java 1.7+ 错误]
- reactjs - 从可重用组件传递 ref