drawable フォルダーには多くのアイコンがあり、その名前は文字列です。drawable フォルダーにアクセスして背景の imageView (または任意のビュー) を変更するには、これらの名前を動的に使用する方法を教えてください。ありがとう
31791 次
6 に答える
34
これは、リフレクションを使用して実行できます。
String name = "your_drawable";
final Field field = R.drawable.getField(name);
int id = field.getInt(null);
Drawable drawable = getResources().getDrawable(id);
または使用Resources.getIdentifier():
String name = "your_drawable";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);
次に、どちらの場合でもドローアブルを設定するためにこれを使用します。
view.setBackground(drawable)
于 2014-02-18T14:13:30.017 に答える
7
int resId = getResources().getIdentifier("your_drawable_name","drawable",YourActivity.this.getPackageName());
Drawable d = YourActivity.this.getResources().getDrawable(resId);
于 2014-02-18T14:12:07.570 に答える
5
次のように実行できます。
ImageView imageView = new ImageView(this);
imageView.setBackground(getResources().getDrawable(getResources().getIdentifier("name","id",getPackageName())));
于 2014-02-18T14:11:03.627 に答える
3
これを試して:
public Bitmap getPic (int number)
{
return
BitmapFactory.decodeResource
(
getResources(), getResourceID("myImage_" + number, "drawable", getApplicationContext())
);
}
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
于 2014-02-18T14:11:48.410 に答える
1
ファイル名が文字列の場合は、次を使用できます。
int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());
このIDを使用すると、いつものようにアクセスできます(ドローアブルと仮定):
Drawable drawable = getResources().getDrawable(id);
于 2014-02-18T14:09:50.620 に答える
0
@FD_の例を使用して、どのアクティビティにもない場合のユースケース
ノート:
"getResources()" または "getPackageName()" を使用するためにコンテキスト パラメータを送信する必要があるアクティビティに参加しておらず、"getDrawable(id)" が非推奨である場合は、代わりに getDrawer(int id, Theme theme) を使用してください。(テーマは null にすることができます):
String name = "your_drawable";
int id = context.getResources().getIdentifier(name, "drawable",
context.getPackageName());
Drawable drawable = context.getResources().getDrawable(id, null);
于 2016-07-14T18:23:58.757 に答える