【问题标题】:change font of textview via menu subitem onclick通过菜单子项 onclick 更改 textview 的字体
【发布时间】:2019-05-13 09:30:05
【问题描述】:

当我单击菜单子项中的相应项目时,我想更改 textview 的字体类型。我有字体选项 Kadwa、Vollkorn 和 Default,它们是 droid sans。我已经能够在点击时显示吐司。我是 android studio 的新手,下面是我的代码,我附上了下面的截图。不知道下一步该做什么。谢谢你的帮助。 Image

@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>

【问题讨论】:

标签: java android android-studio radio-button


【解决方案1】:
//create font using font from asset

Typeface font = Typeface.createFromAsset(
getContext().getAssets(), 
"fonts/androidnation.ttf");

textview.setTypeface(font);

【讨论】:

  • 谢谢,但我是否将其放在菜单项案例中以在单击时启动字体更改?
【解决方案2】:

TextView 上使用 setTypeFace 方法。

您可以通过以下方式获取字体/字体:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多