2016-02-13 68 views
0

我想通過一個字符串找到一種設置imageview的方法。看來,getResources()已被棄用,我似乎無法找到傳遞字符串並將圖像加載到imageView的快速方法。我沒有任何工作或有用的代碼來呈現,我只是要求研究方法。 謝謝!從Android Studio中的字符串中獲取可繪製對象

+1

對不起,這個問題對我來說毫無意義。你能指出我確切的哪個getResources被棄用的文檔嗎?你打算如何將字符串轉換爲圖像? –

+0

這裏是一個例子: http://stackoverflow.com/questions/5254100/how-to-set-an-imageviews-image-from-a-string 我有我想要訪問的圖像的名稱,所以我希望通過他們的名字從drawable中獲取它們。 – user1519194

+0

我無法在文檔中看到有關'getResources()'被棄用的任何內容:http://developer.android.com/reference/android/content/Context.html#getResources() – PPartisan

回答

1

theMatus的答案是正確的。通過int標識符訪問可繪製的圖形(即R.drawable.some_image將具有相應的int值)。要轉換String到這樣一個值,你可以使用Resources.getIdentifier()

String mDrawableName = "some_image"; 
int resId = getResources().getIdentifier(mDrawableName , "drawable", getPackageName()); 

要訪問Drawable,你會使用getResources().getDrawable(resId)getResources()不被棄用的方式,雖然getDrawable(int id)在技術上是API 22(它仍然會工作)。如果你想正確看待這一點,並得到各地棄用,你可以使用以下命令:

@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1) 
private Drawable getDrawableForSdkVersion(int resId, Resources res) { 

    Drawable drawable = null; 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { 
     drawable = res.getDrawable(resId, null); 
    } else { 
     drawable = res.getDrawable(resId); 
    } 

    return drawable; 

} 
1

使用API​​ 22'getResources()'已棄用。你可以使用它,它也向後兼容,所以你可以安全地移動到這個方法。

ContextCompat.getDrawable(context, R.drawable.<you_name_it>) 

更新:

也忘了提,你可以用畢加索加載您的字符串(旨在圖片的路徑)到imageviews。

這裏一個小例子:

ImageView imageView1 = (ImageView) findViewById(R.id.myImageView); 
Picasso.with(getApplicationContext()).load("www.pictures.com/picture.jpg").into(imageView1); 

可以使畢加索一個小的搜索位置:http://square.github.io/picasso/

何況,但#1 Android應用程序也使用這個庫,必須具備的圖書館之一在Android中。

+0

謝謝,但我將如何動態訪問我的圖像?我想通過一個字符串,而不是靜態的 – user1519194

+0

我更新了答案,畢加索將幫助您 – 2016-02-13 08:29:01

+1

我允許使用畢加索商業嗎?我無法告訴 – user1519194

0
ImageView imgView = (ImageView) findViewById(R.id.imageView); 
imgView.setImageDrawable(ContextCompat.getDrawable(currentActivity.this,R.drawable.your_image)); 

其實theMatus回答你的問題。此代碼適用於不推薦使用的問題。

相關問題