我怎样才能获得图像名称?

时间:2016-02-05 21:14:50

标签: android

我有一个Button和imageView,当我点击按钮时,在imageview中似乎有1个随机图像。然后它的名字将出现在textView ...

        ImageView img=(ImageView)findViewById(R.id.logolar);
        Random rand = new Random();
        int rndInt = rand.nextInt(5) + 1;
        String drawableName = "image"+ rndInt;
        int resID = getResources().getIdentifier(drawableName, "drawable", getPackageName());
        img.setImageResource(resID);

        TextView logoismi = (TextView)findViewById(R.id.logoismi);
        logoismi.setText(lastImageName);
        clickeddata.add(logoismi.getText().toString());

        lastImageName = drawableName;

但是使用此代码,我的图像名称必须是; image1,image2,image3 ......我不想要它。我的图片有不同的名字。所以我可以用这段代码获得不同的图像名称;

    final Class drawableClass = R.drawable.class;
final Field[] fields = drawableClass.getFields();

final Random rand = new Random();
int rndInt = rand.nextInt(fields.length);
try {
    int resID = fields[rndInt].getInt(drawableClass);
    img.setImageResource(resID);
} catch (Exception e) {
    e.printStackTrace();
}

但我也无法使用此代码在textView中获取图像名称。我该如何解决所有问题?

1 个答案:

答案 0 :(得分:0)

使用此

getResources().getResourceEntryName(int resid);

getResources().getResourceName(int resid);

您的代码应为

try {
    int resID = fields[rndInt].getInt(drawableClass);
    img.setImageResource(resID);
    String lastImageName = getResources().getResourceEntryName(resID);
    //String lastImageName = getResources().getResourceName(resID); // You can use this too
    TextView logoismi = (TextView)findViewById(R.id.logoismi);
    logoismi.setText(lastImageName);
} catch (Exception e) {
    e.printStackTrace();
}

<强>更新

创建一个像

的图像ID数组

保存在res/values/arrays.xml

的XML文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="my_array">
        <item>@drawable/rose</item>
        <item>@drawable/book</item>
        <item>@drawable/pen</item>
    </array>
</resources>

像这样阅读

TypedArray ar = context.getResources().obtainTypedArray(R.array.my_array);
int len = ar.length();
int[] resIds = new int[len];
for (int i = 0; i < len; i++)
    resIds[i] = ar.getResourceId(i, 0);
ar.recycle();

在您的代码中使用它

Random rand = new Random();
int rndInt = rand.nextInt(resIds.length) + 1;
try {
    int resID = resIds[rndInt];
    img.setImageResource(resID);
    String lastImageName = getResources().getResourceEntryName(resID);
    //String lastImageName = getResources().getResourceName(resID); // You can use this too
    TextView logoismi = (TextView)findViewById(R.id.logoismi);
    logoismi.setText(lastImageName);
} catch (Exception e) {
    e.printStackTrace();
}