2014-12-03 53 views
0

如果我有這片與硬編碼字符串代碼「重要的新事件」:如何使用res/values/strings.xml中的字符串id而不是String或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 /價值/ string.xml文件,而不是:

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

那麼如何在上面的構造函數中使用R.strings.new_event(並且我知道構造函數已被棄用)?

還有一個問題請 - 爲什麼final以上使用的關鍵字?

回答

3

活動有getString將字符串的ID作爲參數的方法。

變化

"New event of importance" 

getString(R.string.new_event); 

一般訪問的資源,你需要一個上下文對象

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

建立在strings.xml新的字符串(或其他資源文件)

然後你就可以在你的代碼中引用它:

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