【问题标题】:ImageView SetImageResource from string dynamically [duplicate]ImageView SetImageResource 从字符串动态[重复]
【发布时间】:2016-09-12 23:45:41
【问题描述】:

我想从字符串中动态设置 ImageView 资源,但是我无法通过以下方法做到这一点。

我正在使用 Xamarin/Android 动态设置 ImageView 资源,如下所示;

ImageView homeItemImage = convertView.FindViewById<ImageView>(Resource.Id.homeItemImage);
int imageId = PlatformProvider.GetImageId(Context, contentTitle.IconImageUrl);
homeItemImage.SetImageResource(imageId);

GetImageId 函数:

public static int GetImageId(Context context, string imageName)
{
//   int identifier = context.Resources.GetIdentifier(imageName, "drawable", context.PackageName);
int identifier = context.Resources.GetIdentifier(context.PackageName + ":drawable/" + imageName, null, context.PackageName);
return identifier;
}

我将 imageName 都传递为“Account.png”或“Account”都返回 int 为 0。

这是我的图片文件夹:

我将它们设置为 AndroidResource(这里显示的是 About.png 但 Account.png 是相同的方式):

它们以智能感知显示:

如何从字符串中设置图片来源?

【问题讨论】:

  • 特别是this answer
  • @Code-Apprentice 这个答案就是我要找的答案。这是 xamarin 方面的一个奇怪的实现。感谢您指出。

标签: android xamarin imageview


【解决方案1】:

资源必须not contains special character ->

文件夹内的每个文件都被翻译成里面的java字段名 R.java 类:

drawable\icon.png -> R.drawable.icon 因此不使用的原因 文件名中的特殊字符,因为它们不能在 Java 中使用 名字。

至于大写字母,我想这是为了避免一个小问题 Windows 与 Linux 环境。那是因为 Linux 认为 Icon.png 和 icon.png 是不同的文件,Windows 认为 Icon.png 和 icon.png 是同一个文件。所以任何使用 Linux 的人都可以 创建无法在 Windows 上编译的应用程序。

【讨论】:

  • 是的,这是我尝试的第一个选项; context.Resources.GetIdentifier(imageName, "drawable", context.PackageName);它仍然始终返回 0。
  • 但是你为什么要做 context.Ressources 而不是 context.getRessources() ?
  • 你的意思是 context.PackageName?它是 Android 上的 Xamarin 实现,我检查它返回正确的包名称。
  • 是的,你是对的,你试过不用大写字母吗?它可能会导致问题,因为它是一个特殊字符。与此相关-> stackoverflow.com/questions/6758228/…
  • 这更清楚地解释了奇怪之处,谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-11-12
  • 2019-12-26
  • 2017-02-17
  • 2011-05-17
  • 1970-01-01
  • 2015-12-28
  • 2020-07-03
  • 1970-01-01
相关资源
最近更新 更多