【问题标题】:Change ImageButton Drawable automatically自动更改 ImageButton Drawable
【发布时间】:2017-05-29 06:49:26
【问题描述】:

我在 drawable 目录和 ImageButton 中有 320 张图片,所以当它被点击时,图片必须随机更改,图片名称是这样的file_xyzxyz 是使用此代码随机生成的数字:

rand = new Random(System.currentTimeMillis());
x = rand.nextInt(3 - 0) + 0;
y = rand.nextInt(7 - 0) + 0;
z = rand.nextInt(9 - 0) + 0;
return "shape_" + x+ y+ z;

所以这给了我一个字符串,我想用它来更改 ImageButton 的资源,那么如何应用它并在不同的时间随机进行更改?

【问题讨论】:

    标签: android random android-imagebutton


    【解决方案1】:

    试试这个:

       int resID = getResources().getIdentifier(pDrawableName , "drawable", getPackageName());    
        imageview.setBackgroundResource(resID);
    

    String pDrawableName = file_xyz 是您的图片名称

    【讨论】:

    • 我正在尝试这个,但是当我编写这段代码时,getResources() 不仅仅显示getClass()@rafsanahmad007
    • 使用getApplicationContext().getResources()
    • getApplicationContext()@rafsanahmad007
    • 你在片段中使用它吗?
    • 然后试试getActivity().getResources()...
    【解决方案2】:

    如果您首先在可绘制文件夹中创建确切的文件名字符串(我将其称为字符串图像),您可以执行以下操作:

    ImageButton imageButton = (ImageButton) findViewById(R.id.image_button);
    imageButton.setImageResource(R.drawable.image);
    

    其中 image_button 是您为图像按钮设置的 ID。

    【讨论】:

    • 您检查生成的图片名称是否与您的drawable文件夹中的图片名称完全匹配?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2013-11-21
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多