Snackbar操作文本颜色未发生变化

46

我想改变我的 Snackbar 的操作文本颜色,但出于某些原因它无法工作。

我使用以下代码显示 Snackbar:

Snackbar.make(findViewById(R.id.root), "text", Snackbar.LENGTH_LONG).setActionTextColor(R.color.yellow).setAction("OK", new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    }
}).show();
5个回答

92
setActionTextColor方法的参数是代表颜色的int值,而非资源ID。

不要这样写:

.setActionTextColor(R.color.yellow)

尝试:

.setActionTextColor(Color.YELLOW)

如果您仍然想使用资源,请尝试:

.setActionTextColor(ContextCompat.getColor(context, R.color.color_name));

注意:要使用ContextCompat,我假设你已经将支持库包含到了你的build.gradle文件中(如果你已经有AppCompat(v7)库,这是可选的)。

3
snackbar.setActionTextColor(getResources().getColor(R.color.colorPrimary)); 这对我起作用了....! - Prasad
只有在OP对“黄色”的定义与系统相同的情况下,这才有效。 - tir38
关于getColor被弃用的问题,不要使用@SuppressWarning,而是使用ContextCompat.getColor(context, R.color.youColor)。 - Rafi Panoyan
你正在将一个颜色资源引用分配给Snackbar (@ColorRes),但是如果你查看方法#setActionTextColor,它要求一个@ColorInt整数,这基本上要求直接提供颜色的十六进制表示。 - Ricard

28
.setActionTextColor(getResources().getColor(R.color.red))

仅仅是而已

.setActionTextColor(R.color.red)

22
getColor(int)已被弃用,请改用ContextCompat.getColor(context, R.color.red)。该方法具有相同的功能,但更为推荐。 - Hafez Divandari

6

以上回答都没有帮到我。我找到了这个解决方案,通过手动更改TextView的文本颜色来解决问题。

Snackbar snack = Snackbar.make(v, "Snackbar message", Snackbar.LENGTH_LONG);
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
tv.setTextColor(Color.WHITE);
snack.show();

如果有人想使用相同的技巧来更改操作按钮,只需添加类似于“TextView action = view.findViewById(android.support.design.R.id.snackbar_action); action.setTextColor(view.getContext().getResources().getColor(android.R.color.holo_red_dark));”这样的内容。 - mtsahakis

1
如果您想更改操作按钮文本的颜色...
snackbar.setActionTextColor(getResources().getColor(R.color.colorAccent));

如果您想更改操作按钮的背景颜色...
View sbView = snackbar.getView();
Button button=
(Button) sbView.findViewById(com.google.android.material.R.id.snackbar_action);
button.setBackgroundColor(getResources().getColor(R.color.white));

0

试试这个,

 Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Permission required!", 3000 /*Snackbar.LENGTH_INDEFINITE*/);
 snackbar.setAction("OK", new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // perform any action when the button on the snackbar is clicked
            Toast.makeText(MainActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show();
        }
    });
 snackbar.setBackgroundTint(getResources().getColor(R.color.black));      // set the background tint color for the snackbar
 snackbar.setActionTextColor(getResources().getColor(R.color.purple_500)); // set the action button text color
 snackbar.show();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接