0

如果我有这段带有硬编码字符串“重要的新事件”的代码:

public class MainActivity extends Activity {
    private NotificationManager mNManager;
    private static final int NOTIFY_ID = 1100;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String ns = Context.NOTIFICATION_SERVICE;
        mNManager = (NotificationManager) getSystemService(ns);
        final Notification msg = new Notification(R.drawable.ic_launcher,
                "New event of importance",
                System.currentTimeMillis());

但想将其移动到res/values/string.xml文件中:

<string name="new_event">New event of importance</string>

那么如何R.strings.new_event在上面的构造函数中使用(是的,我知道构造函数已被弃用)?

请再问一个问题 - 为什么final上面使用关键字?

4

4 回答 4

3

Activity 具有getString将字符串的 id 作为参数的方法。

改变

  "New event of importance"

 getString(R.string.new_event);

通常要访问资源,您需要一个上下文对象

于 2014-12-03T13:49:16.123 回答
2

用这个

String Name=getResources().getString(R.string.new_string)

并查看此处的文档http://developer.android.com/guide/topics/resources/string-resource.html

于 2014-12-03T13:49:36.723 回答
1

在您的 strings.xml(或其他资源文件)中创建新字符串

然后你可以在你的代码中引用它:

Context context = getApplicationContext();
Resources res = context.getResources();
String newEvent = res.getString(R.string.new_event)
于 2014-12-03T13:55:23.800 回答
1
String str = context.getResources().getString(R.string.your_string_id)
于 2014-12-03T13:53:34.937 回答