根据情况设置ImageView
我已经寻找了一段时间,但找不到解决我的问题的方法。我正在尝试根据登录的用户设置 imageView。主要问题是如何将 R.drawable.stock
重命名为 R.drawable.user1
其中名称imageView的内容随用户名的不同而变化。我尝试将其设置为像 String temp="R.drawable."+userNameStore;
这样的字符串,但没有运气。
这就是我正在做的事情:
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);
}
i have been looking for a while and could not find a solution for my problem. I am trying to set an imageView depending on the User logged in. The main problem is how do i rename R.drawable.stock
into R.drawable.user1
where the name of the imageView varies with the name of the user. I tried setting it to a string like String temp="R.drawable."+userNameStore;
but did not have luck.
Here is what i am doing:
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为此,我在实用程序类中使用了 2 个方法:
因此,如果您的可绘制文件夹中有一个名为
user1
的图像资源,您可以像这样获取和使用它的 ID:imageView.setImageResource(getImageId) (这个,“用户1”));
I use 2 methods in my utility class for this:
So if you have an image resource in your drawable folder named
user1
, you could get and use its ID like this:imageView.setImageResource(getImageId(this, "user1"));
您可以使用 getIdentier,例如:
检查文档 here
在您的情况下,它应该类似于:
You can use getIdentier, for example:
Check the documentation here
In your case it should be something like:
您可以像这样构造字符串标识符...
int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());
它涵盖了 这里
You can construct your string identifier like this...
int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());
It's covered here