改变小吃店的字体

use*_*211 17 android android-snackbar

我通过以下代码构建了snackbar:

Snackbar sb = Snackbar.make(drawer,  "message", Snackbar.LENGTH_LONG)
                .setAction("action", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                });
Run Code Online (Sandbox Code Playgroud)

现在我想更改消息和操作按钮的字体,但找不到任何解决方案,怎么做?

Ash*_*wal 34

您可以通过从小吃栏获取视图来设置TypeFace

TextView tv = (TextView) (mSnackBar.getView()).findViewById(android.support.design.R.id.snackbar_text);
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/font_file.ttf");
tv.setTypeface(font);
Run Code Online (Sandbox Code Playgroud)


Sur*_*nav 12

对于AndroidX

android.support.design.R.id.snackbar_text 将不可用。

使用 com.google.android.material.R.id.snackbar_text来代替。

如果您使用 kotlin,那么我更喜欢您使用扩展功能:

fun Snackbar.changeFont()
{
    val tv = view.findViewById(com.google.android.material.R.id.snackbar_text) as TextView
    val font = Typeface.createFromAsset(context.assets, "your_font.ttf")
    tv.typeface = font
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

mSnakeBar.changeFont()
Run Code Online (Sandbox Code Playgroud)

  • createFromAsset 对我不起作用,应用程序每次崩溃都说找不到我的字体,我使用 ResourceCompat 中的 getFont,就像这样 `val font = ResourcesCompat.getFont(context, R.font.my_font)` (2认同)

Jos*_*ter 10

设置小吃文本和动作的样式

您可以使用相同的方法来设置snackbar_textsnackbar_action.

创建快餐栏后,您可以使用以下内容获取与文本和操作关联的视图,然后对视图应用任何调整.

Snackbar snackbar = Snackbar.make( ... )    // Create the Snackbar however you like.

TextView snackbarActionTextView = (TextView) snackbar.getView().findViewById( android.support.design.R.id.snackbar_action );
snackbarActionTextView.setTextSize( 20 );
snackbarActionTextView.setTypeface(snackbarActionTextView.getTypeface(), Typeface.BOLD);

TextView snackbarTextView = (TextView) snackbar.getView().findViewById(android.support.design.R.id.snackbar_text);
snackbarTextView.setTextSize( 16 );
snackbarTextView.setMaxLines( 3 );
Run Code Online (Sandbox Code Playgroud)

在我的示例中,我将Action设置为字体大小20和Bold,并将Text设置为大小16并允许最多3行.


STA*_*YER 5

除了这个答案:现在通过 id 查找 Snackbar's textview 的包是

val snackText = snackView.findViewById<TextView>(
                    com.google.android.material.R.id.snackbar_text)
Run Code Online (Sandbox Code Playgroud)