2011-11-30 48 views
0

我一直在尋找一段時間,找不到解決方案,我的問題。我試圖根據用戶登錄設置imageView。主要問題是,如何將R.drawable.stock重命名爲R.drawable.user1,其中imageView的名稱因用戶的名稱而異。我試圖將其設置爲像String temp="R.drawable."+userNameStore;這樣的字符串,但沒有運氣。根據情況設置ImageView

下面是我在做什麼:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.profile); 

    SharedPreferences app_preferences = 
     PreferenceManager.getDefaultSharedPreferences(this); 
    String userNameStore = 
     app_preferences.getString("userNameStore", null); 

    String temp="R.drawable."+userNameStore; 

    TextView textName=(TextView) findViewById(R.id.username); 
    textName.setText("Username: "+ userNameStore); 
    ImageView image = (ImageView) findViewById(R.id.imageView1); 
      image.setImageResource(temp); 
} 

回答

0

我用我的實用工具類2種方法是:

public static int getImageId(Context context, String imageName) { 
    return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName()); 
} 

public static int getRawResourceId(Context context, String rawName) { 
    return context.getResources().getIdentifier("raw/" + rawName, null, context.getPackageName()); 
} 

所以,如果你在你的名爲user1繪製文件夾中的圖片資源,你可以得到並使用其ID像這樣:

imageView.setImageResource(getImageId(this, "user1"));

+0

謝謝,這工作完美 – user1074039

0

您可以使用getIdentier,例如:

getResources().getIdentifier("star_off", "string", getPackageName()); 

檢查文檔here

你的情況應該是這樣的:

int resID = getResources().getIdentifier(temp, "drawable", getPackageName()); 
... 
image.setImageResource(resID); 
+0

謝謝,這個工作完美 – user1074039

+0

很高興它的工作! – gwa

0

您可以像這樣構造您的字符串標識符...

int id = getResources()。getIdentifier(「name_of_resource」,「id」,getPackageName());

它覆蓋here