单击菜单子项更改文本视图的字体



当我单击菜单子项中的相应项时,我想更改文本视图的字体类型。我有字体选项Kadwa、Vollkorn和Default,即droid sans。我已经可以点击显示吐司了。我是安卓工作室的新手,下面是我到目前为止的代码,我在下面附上了一张截图。不知道下一步该做什么。谢谢你的帮助。图像

@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);
}

菜单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="Kadwa"/>
<item android:id="@+id/font2"
android:title="Vollkorn"/>
<item android:id="@+id/font3"
android:title="Default"/>
</menu>
</item>

</menu>

</item>
//create font using font from asset
Typeface font = Typeface.createFromAsset(
getContext().getAssets(), 
"fonts/androidnation.ttf");
textview.setTypeface(font);

TextView上使用setTypeFace方法。

你可以通过获取字体

ResourcesCompat.getFont(this, R.font.fontnamehere)

最新更新