如何使用res / values / strings.xml中的字符串id而不是String或CharSequence?

时间:2014-12-03 13:47:08

标签: android string android-resources final charsequence

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

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 个答案:

答案 0 :(得分:3)

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

更改

  "New event of importance"

 getString(R.string.new_event);

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

答案 1 :(得分:2)

使用此

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

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

答案 2 :(得分:1)

String str = context.getResources().getString(R.string.your_string_id)

答案 3 :(得分:1)

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

然后您可以在代码中将其引用为:

Context context = getApplicationContext();
Resources res = context.getResources();
String newEvent = res.getString(R.string.new_event)