【问题标题】:Placing String from strings.xml in the Toast Message将来自 strings.xml 的字符串放入 Toast 消息中
【发布时间】:2017-05-27 17:35:33
【问题描述】:

我目前正在完成我的安卓游戏应用程序,但我遇到了一个问题,导致我的应用程序不断崩溃。

我试图将 strings.xml 中的文本放入 toast 消息中,我的代码如下所示:

    // THIS IS THE PART THAT DOES NOT WORK:
    int stringrank = getResources().getIdentifier("rank"+points, "string", this.getPackageName());
    rank = getString(stringrank);
    // I want to get different rank String depending on the collected points, 
    // so it would be rank1, rank2, rank3 and so on - thats why "rank"+points.
    // It worked for me in the different parts of the code, but when I want to
    // use it in the Toast Message it does not.


    LayoutInflater inflater = getLayoutInflater();
    View layout = inflater.inflate(R.layout.done_toast, (ViewGroup) findViewById(R.id.done_toast));
    TextView text = (TextView) layout.findViewById(R.id.text);
    // APP CRASHES when I use "rank" String here, if I place other text it works just fine.
    text.setText(rank);

    final Toast donetoast = new Toast(getApplicationContext());
    donetoast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 35);
    donetoast.setDuration(Toast.LENGTH_SHORT);
    donetoast.setView(layout);
    // Rest of the Toast Message code is below, not important.
    (...)

当我将普通文本放在 Toast 消息中时(无论是在 Java 中还是在 done_toast.xml 中),它都能完美运行,但如果我想 从 strings.xml 调用字符串,应用程序就会崩溃。

提前感谢您的帮助!

【问题讨论】:

  • 向我们展示崩溃的 logcat 输出,以便我们知道异常是什么以及它发生在哪一行代码上。
  • 好的,我仔细检查了日志,这完全是愚蠢的错误,与 Java 代码无关。 strings.xml 中的“rank”字符串在“sp”中的字体大小为:ROOKIE 虽然它应该是简单的“16”。纠正了它,它工作得很好。很抱歉打扰各位,请大家帮忙!

标签: java android xml string toast


【解决方案1】:

你不能像那样创建一个 Toast 对象。必须使用 Toast.makeText() 来完成。

试试这个

final Toast donetoast=Toast.makeText(getApplicationContext());
donetoast.setDuration(Toast.LENGTH_SHORT);
donetoast.setView(layout);

【讨论】:

  • 它是为游戏(图形等)定制的吐司,带有与之关联的单独 .xml 文件。它运行良好(我在代码中已经有 4 条不同的 toast 消息)当我想将字符串从 strings.xml 文件放入其中时它会崩溃。如果我将它写在 toast 消息中,或者我在 toast.xml 文件中指定它,它就可以正常工作。问题是关于“等级”字符串。
  • 请放logcat
  • 好的,我仔细检查了日志,这完全是愚蠢的错误,与 Java 代码无关。 strings.xml 中的“rank”字符串在“sp”中的字体大小为:ROOKIE 虽然它应该是简单的“16”。纠正了它,它工作得很好。很抱歉打扰你的队友,欢呼帮助!
  • 完全没有问题
猜你喜欢
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 1970-01-01
相关资源
最近更新 更多