在我的应用程序中,我需要在某些地方获取一些位图drawable,我不想保留引用R
.所以我创建了一个类DrawableManager
来管理drawables.
public class DrawableManager {
private static Context context = null;
public static void init(Context c) {
context = c;
}
public static Drawable getDrawable(String name) {
return R.drawable.?
}
}
Run Code Online (Sandbox Code Playgroud)
然后我想通过这个名字得到drawable(car.png放在res/drawables中):
Drawable d= DrawableManager.getDrawable("car.png");
Run Code Online (Sandbox Code Playgroud)
但是正如您所看到的,我无法通过名称访问资源:
public static Drawable getDrawable(String name) {
return R.drawable.?
}
Run Code Online (Sandbox Code Playgroud)
任何替代品?
ian*_*ake 148
请注意,您的方法几乎总是错误的做事方式(更好地将上下文传递给使用drawable的对象本身,而不是在Context
某处保持静态).
鉴于此,如果要进行动态可绘制加载,可以使用getIdentifier:
Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(name, "drawable",
context.getPackageName());
return resources.getDrawable(resourceId);
Run Code Online (Sandbox Code Playgroud)
ssa*_*tos 22
你可以这样做.-
public static Drawable getDrawable(String name) {
Context context = YourApplication.getContext();
int resourceId = context.getResources().getIdentifier(name, "drawable", YourApplication.getContext().getPackageName());
return context.getResources().getDrawable(resourceId);
}
Run Code Online (Sandbox Code Playgroud)
为了从任何地方访问上下文,您可以扩展Application类.-
public class YourApplication extends Application {
private static YourApplication instance;
public YourApplication() {
instance = this;
}
public static Context getContext() {
return instance;
}
}
Run Code Online (Sandbox Code Playgroud)
并将其映射到您的Manifest
application
标签中
<application
android:name=".YourApplication"
....
Run Code Online (Sandbox Code Playgroud)
小智 7
修改图片内容:
ImageView image = (ImageView)view.findViewById(R.id.imagenElement);
int resourceImage = activity.getResources().getIdentifier(element.getImageName(), "drawable", activity.getPackageName());
image.setImageResource(resourceImage);
Run Code Online (Sandbox Code Playgroud)
使用 Kotlin
fun Context.getResource(name:String): Drawable? {
val resID = this.resources.getIdentifier(name , "drawable", this.packageName)
return ActivityCompat.getDrawable(this,resID)
}
Run Code Online (Sandbox Code Playgroud)
我把它写成扩展函数,所以它可以在代码的任何地方使用。
注:context.getResources().getDrawable(resourceId);
被弃用Java编写的。
注意:文件名,是不带扩展名的名称,例如“a.png”名称将是“a”。
归档时间: |
|
查看次数: |
57288 次 |
最近记录: |