【问题标题】:How to use Snackbar in a relative layout instead of Toasts?如何在相对布局中使用 Snackbar 而不是 Toasts?
【发布时间】:2018-10-20 08:45:44
【问题描述】:

我正在尝试在相对布局中使用 Snackbar 而不是 Toasts 来显示错误(如果输入字段为空)。但我无法添加小吃店来代替 Toast。

下面是我的 Toasts 代码 -

if (abc_value.equals("") || def_value.equals("") || ghi_value.equals("")) {
    Toast.makeText(getApplicationContext(), "Please enter all fields", Toast.LENGTH_SHORT).show();
} else {
    Intent intent = new Intent(getApplicationContext(), next.class);

如果 3 个字段中的任何一个为空,它将显示字符串消息,否则它将导航到下一个活动。

编辑 -

  1. 第一次尝试:

    Snackbar.make(getActivity().getWindow().getDecorView().getRootView(), "Test", Snackbar.LENGTH_LONG).show();
    

这不是因为它不接受 rootview - 我觉得这是最接近的。

  1. Snackbar.make(findViewById(Ids), "Test", Snackbar.LENGTH_LONG)
                            .setAction("Undo", mOnClickListener)
                            .setActionTextColor(Color.RED)
                            .show();
    

尝试使用 ID 但它不接受。

  1. Snackbar snackbar = Snackbar
        .make(coordinatorLayout, "Welcome to AndroidHive", Snackbar.LENGTH_LONG);
    
    snackbar.show();
    

不能使用这个,因为我没有使用 coordinatorLayout。

【问题讨论】:

  • 您是否至少尝试过用 Google 搜索:android snackbar
  • 您知道在询问之前您必须搜索,对吧?
  • @pskink 如果没有谷歌搜索,我就不会来这里。我已经提到了我正在做的事情,希望是令人满意的
  • 好吧,正如你们所有人都提到的,我还没有对此进行任何研究,我正在编辑我的问题,并会在来这里之前添加我使用过的内容:)
  • @AbhishekDS 您提供的代码没有 Snackbar 类使用。我建议在使用 android 中的新类时先看看它developer.android.com

标签: android android-snackbar


【解决方案1】:

试试这个:

     if (abc_value.equals("") || def_value.equals("") || ghi_value.equals("")) {

            Snackbar snackbar = Snackbar.make(yourMainLayout, 
            "Please enter all fields!", Snackbar. LENGTH_SHORT);

            // Changing action button text color
            View sbView = snackbar.getView();
            TextView textView = (TextView) 
            sbView.findViewById(android.support.design.R.id.snackbar_text);
            textView.setTextColor(Color.YELLOW);
            snackbar.show();
        }

        else {
            Intent intent = new Intent(getApplicationContext(), next.class);
        }

【讨论】:

  • 您发布了一个与 coordinatorLayout 的使用有关的答案,正如我在问题的详细信息中提到的那样,该答案没有被使用。
  • coordinatorLayout 是你的主要布局,它是 relativeLayout,不是吗?
【解决方案2】:
Snackbar snackbar = Snackbar
    .make("id of root layout", "content of displayed message", Snackbar.LENGTH_LONG);

snackbar.show();

【讨论】:

  • 就是这样。更新了您的答案,以消除要使用的 ID 的混淆:)
  • 我的答案是一样的 yourMainLayout :(
  • @propoLis,不,你的答案更好,因为它是一个 完整 工作代码,而不是作者使用 "id of your root layout control" 的这个答案(无论它是什么意思) - 我不知道为什么它是公认的答案
【解决方案3】:

if里面试试这个

Snackbar snackbar = Snackbar.make(rootLayout, "your error", Snackbar.LENGTH_LONG);
snackbar.show();

【讨论】:

  • 无法解析符号根布局是我尝试此操作时得到的结果!
  • rootLayout 表示您的活动的主要布局。
  • 即使我用RelativeLayout替换它,它也会显示同样的错误
  • 你必须先做一个相对布局实例,比如Relativelayout relative;然后 findViewById() 它。
  • 我使用了类名,它起作用了,而不是通过相对布局找到它。
猜你喜欢
  • 2017-02-02
  • 2018-01-22
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
相关资源
最近更新 更多