如何打印可绘制的图像名称

时间:2016-02-03 22:32:33

标签: android

我有一个带有1个textview,1个imageview和1个按钮的布局。我有5张可绘画的照片。他们的名字如image1,image2,image3 ......当我点击按钮时,按钮改变了drawable中的随机图片(“image”+ rand。数字方法)但我想将更改后的图像名称打印到textview。我该怎么做? *简单;按钮功能:首先打印现有图像>然后改变新的随机图像。 **对不好的语法我很抱歉..

public void onClick(View v) {
    ImageView img=(ImageView)findViewById(R.id.imageView1);
    Random rand = new Random();
    int rndInt = rand.nextInt(5) + 1;
    String drawableName = "image"+ rndInt;
    int resID = getResources().getIdentifier(drawableName, "drawable", getPackageName());
    img.setImageResource(resID);
};

1 个答案:

答案 0 :(得分:0)

使用以下代码,您将始终可以看到当前显示的图像名称:

String  lastImageName = "";

public void onClick(View v) {
    ImageView img=(ImageView)findViewById(R.id.imageView1);
    Random rand = new Random();
    int rndInt = rand.nextInt(5) + 1;
    String drawableName = "image"+ rndInt;
    int resID = getResources().getIdentifier(drawableName, "drawable", getPackageName());
    img.setImageResource(resID);

    // just set the text in the textview. You need to have it in your layout xml of course
    TextView textView = (TextView)findViewById(R.id.logoismi);
    textView.setText(lastImageName);

    lastImageName = drawableName;
}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/bos"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/dogru"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="BOŞ" />

    <ImageView
        android:id="@+id/logolar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/bos"
        android:layout_marginBottom="70dp"
        android:maxHeight="800dp"
        android:maxWidth="800dp"      
        android:layout_centerInParent="true"
        android:scaleType="centerInside"
        android:src="@drawable/image1" />

    <TextView
        android:id="@+id/logoismi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/dogru"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="52dp"
        android:text="image1" />

</RelativeLayout>