无法在 Java (Android) 中引用 XML 字符串资源

Cannot reference an XML string resource in Java (Android)

我一辈子都弄不明白为什么这不起作用。我试图在我的 Java 代码中引用我的 strings.xml 文件中的字符串。出于某种原因,我可以引用同一 xml 文件中的每个字符串,但我需要引用的两个字符串除外。我不知道我是否说清楚了,但下面是我当前的代码,所以我可以更好地展示它:

MainActivity.java

package bcs421.jorgeramirez.hwk.hellogoodbye;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button greetButton = (Button)findViewById(R.id.greetingButton);
    Button goodbyeButton = (Button)findViewById(R.id.goodbyeButton);
    greetButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Toast greeting;
            Context context;
            CharSequence text = getString(R.string.greeting_toast);
            int duration = Toast.LENGTH_SHORT;
            greeting.makeText(context, text, duration);

        }
    });
}
}

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">Hello/Goodbye</string>
<string name="hello_world">Hello world!</string>
<string name="language">English</string>
<string name="greeting_msg">Greetings!</string>
<string name="goodbye_msg">Goodbye!</string>
<string name="greeting_toast">Hello!</string>
<string name="goodbye_toast">See you later!</string>

</resources>

顺便说一句,我的项目还没有完成,但我不知道为什么 getString(R.string.greeting_msg);

有效,但

getString(R.string.greeting_toast);

将不起作用。我的 XML 文件中的所有其他字符串都可以在我的 Java 文件中引用,除了最后两个 "greeting_toast" 和 "goodbye_toast"。任何帮助将不胜感激!!提前致谢!

  1. 您的项目是否包含错误以致无法构建并且无法重新生成 R?
  2. 确保不同地区/分辨率的其他 strings.xml 也包含 R.string.greeting_toast。
  3. 清理并重建您的项目

我不知道它在你的 IDE 上是如何工作的,但我的 Android Studio 显示了一些错误..

删除这一行:

Toast greeting;

你必须得到你的上下文,因为我猜你的代码上下文是空的。

然后你必须通过添加 .show()

来展示你的吐司
Context context = getApplicationContext();
CharSequence text = getString(R.string.greeting_toast);
int duration = Toast.LENGTH_SHORT;

Toast.makeText(context, text, duration).show();'

你也可以将它缩短为一行,像这样:

Toast.makeText(getApplicationContext(), R.string.greeting_toast, Toast.LENGTH_SHORT).show();