2012-02-05 108 views
3

我有一個名爲MyPrimaryClass的類,這個類在按下時有一個按鈕,用類myClassForResult創建一個Intent。來自資源字符串的Toast.makeText

我使用它來啓動它:

startActivityForResult(myIntentOfMyClassForResult, ACTIVITY_EDIT_BTEXT); 

兩個MyPrimaryClass和myClassForResult延伸活動。

因此,當我在myClassForResult中調用Toast.makeText時,使用R.string.my_resource_string的文本參數,它給了我強制關閉!

我曾嘗試這樣的:

Context c = myClassForResult.this; 
Toast toast = Toast.makeText(c, 
    c.getResources().getString(R.string.my_resource_string), 
    Toast.LENGTH_SHORT); 
toast.show(); 

同樣在此:C = getApplicationContext()

同樣在此:C = getBaseContext()

同樣在此:

Context c = MyPrimaryClass.this; 
Toast toast = Toast.makeText(c, 
    R.string.my_resource_string, 
    Toast.LENGTH_SHORT); 
toast.show(); 

如果我使用內聯字符串,比如「My Toast Text!」,它就可以工作。但我需要從資源中獲取一個字符串。

- 問題解決:

爲了解決我改變了敬酒的持續時間Toast.LENGTH_LONG

字符串R.string.my_resource_string值是問題「的標題爲空」

當我將它的值更改爲「The title」時,它工作正常,所以我猜這個字符串Toast.LENGTH_SHORT持續時間太長。

但是,當我將持續時間更改爲Toast.LENGTH_LONG時,我可以使用長字符串。

Context c = MyPrimaryClass.this; 
Toast toast = Toast.makeText(c, 
    R.string.my_resource_string, 
    Toast.LENGTH_LONG); 
toast.show(); 
+1

發佈強制關閉的logcat錯誤。 – JoxTraex 2012-02-05 20:28:54

+0

這是logcat錯誤: android.content.res.Resources $ NotFoundException:String資源ID#0x7f04000a – DMF 2012-02-05 20:36:50

+0

你能解釋爲什麼你要使用這兩個類的意義? – JoxTraex 2012-02-05 20:38:25

回答

2

有一點需要注意:

Toast toast = Toast.makeText(c, 
    c.getResources().getString(R.string.my_resource_string), 
    Toast.LENGTH_SHORT); 
toast.show(); 

可以簡化爲:

Toast.makeText(c, 
    c.getResources().getString(R.string.my_resource_string), 
    Toast.LENGTH_SHORT).show(); 

這樣可以節省你,你做的不是一個對象引用需要。

你需要明白的一件事是,只要你在包中引用了R(而不是android.R),只要你有上下文,就可以訪問你的資源。

更新

意識到你正在使用這個,因爲我會建議您 改變你的方法,而這其實可能什麼後,你的做法是不理想的東西那麼簡單。

startActivityForResult(xx)方法通常是當你想啓動一個應用程序在你的包之外的結果。

例如:如果我想獲取從產品的條形碼,然後我會通過一個動作開始的意圖到條碼類,間接。然後我會通過使用onActivityResult(xx)檢索數據。

它使無意識爲您自己的類做到這一點。

+0

這不是答案的人! – iTurki 2012-02-05 20:37:20

+0

我的答案在底部提供。 – JoxTraex 2012-02-05 20:39:13

+0

我有點知道它,但我正在學習Android編程,所以我試圖發佈一個簡單的代碼,避免做一些noob錯誤:) – DMF 2012-02-05 20:39:17

3

嘗試:

Toast.makeText(this, this.getString(R.string.my_resource_string), Toast.LENGTH_SHORT); 
+1

**這**無效,導致代碼是在** View.OnClickListener ** – DMF 2012-02-05 20:31:25

+0

獲取對MyPrimaryClass的引用並使用MyPrimaryClass.getString(R.string.my_resources_string) – ab11 2012-02-05 20:43:07

+0

我這樣做了: 上下文c = MyPrimaryClass.this; 然後c.getString(R.string.my_resources_string) – DMF 2012-02-05 20:45:14

0
Toast.makeText(getApplicationContext(), getApplicationContext().getResources.getString(R.string.imgval), Toast.LENGTH_SHORT).toShow(); 
0

@dilipkaklotar答對,但需要做一些改動:

這是怎樣的工作對我來說

Toast.makeText(getApplicationContext(), 
getApplicationContext().getResources().getString(R.string.message), 
Toast.LENGTH_SHORT).show(); 

的getResources沒有括號()。 ,最後是.show();不要顯示()。

但它是正確的。所以非常感謝你。