2011-11-30 77 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