How to set random images in Imagebutton

Asked

Viewed 1,344 times

1

Guys, I’m trying to make every 0.5s a random image of the folder drawable be set in mine ImageButton but I’m having problems the way I did.

I tried to do it this way: I put the following names in the images in the folder drawable:

button_blue, button_grenn, button_red and button_yeollow

And to set randomly tried using the following code:

package br.com.appteste;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class RunActivity extends ActionBarActivity {

    static Random objectRandomSelect;

    ImageButton imSelect;
    TextView tvSelect;

    int delay = 2000;
    int interval = 500;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_running);

        String[] varButtonImages = {"button_blue","button_grenn","button_red","button_yeollow"};

        final String buttonSelect = varButtonImages[new Random().nextInt(varButtonImages.length)];

        Timer timer = new Timer();

        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                int numberStart = 0;
                int q = 5;


                findViewById(R.id.ImageSelectGame).setBackgroundResource(R.drawable. + buttonSelect);
            }
        }, delay, interval);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

But he does not accept this function here:

findViewById(R.id.ImageSelectGame).setBackgroundResource(R.drawable. + buttonSelect);

Could someone help me?


@Edit

After the help of the ramaral I started to receive this error:

04-17 15:09:44.712: I/art(1032): Background sticky concurrent mark sweep GC freed 2853(221KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 6MB/6MB, paused 2.515ms total 130.397ms
04-17 15:09:45.884: I/Choreographer(1032): Skipped 44 frames!  The application may be doing too much work on its main thread.
04-17 15:09:45.930: D/gralloc_goldfish(1032): Emulator without GPU emulation detected.
04-17 15:09:46.762: I/Choreographer(1032): Skipped 93 frames!  The application may be doing too much work on its main thread.
04-17 15:11:33.771: I/art(1279): Background sticky concurrent mark sweep GC freed 2829(220KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 6MB/6MB, paused 1.475ms total 135.393ms
04-17 15:11:34.354: I/art(1279): Background partial concurrent mark sweep GC freed 187(20KB) AllocSpace objects, 0(0B) LOS objects, 38% free, 6MB/10MB, paused 6.509ms total 108.189ms
04-17 15:11:35.169: I/Choreographer(1279): Skipped 46 frames!  The application may be doing too much work on its main thread.
04-17 15:11:35.211: D/gralloc_goldfish(1279): Emulator without GPU emulation detected.
04-17 15:11:35.669: I/Choreographer(1279): Skipped 52 frames!  The application may be doing too much work on its main thread.
04-17 15:11:40.183: I/Choreographer(1279): Skipped 33 frames!  The application may be doing too much work on its main thread.
04-17 15:11:41.472: I/Choreographer(1279): Skipped 109 frames!  The application may be doing too much work on its main thread.
04-17 15:11:42.079: I/Choreographer(1279): Skipped 65 frames!  The application may be doing too much work on its main thread.
04-17 15:11:44.027: I/art(1279): Background sticky concurrent mark sweep GC freed 2492(161KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 10MB/10MB, paused 1.502ms total 285.036ms
04-17 15:11:44.027: I/art(1279): --------- beginning of crash
04-17 15:11:45.197: E/AndroidRuntime(1279): FATAL EXCEPTION: Timer-0
04-17 15:11:45.197: E/AndroidRuntime(1279): Process: br.com.rigtouch, PID: 1279
04-17 15:11:45.197: E/AndroidRuntime(1279): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
04-17 15:11:45.197: E/AndroidRuntime(1279):     at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6247)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:867)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at android.view.View.requestLayout(View.java:17364)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at android.view.View.requestLayout(View.java:17364)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at android.view.View.requestLayout(View.java:17364)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at android.view.View.requestLayout(View.java:17364)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at android.view.View.requestLayout(View.java:17364)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at android.view.View.requestLayout(View.java:17364)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:360)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at android.view.View.requestLayout(View.java:17364)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at android.view.View.setBackgroundDrawable(View.java:16229)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at android.view.View.setBackground(View.java:16125)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at android.view.View.setBackgroundResource(View.java:16108)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at br.com.rigtouch.RunActivity$1.run(RunActivity.java:43)
04-17 15:11:45.197: E/AndroidRuntime(1279):     at java.util.Timer$TimerImpl.run(Timer.java:284)
04-17 15:11:45.735: I/art(1279): Background partial concurrent mark sweep GC freed 337(39KB) AllocSpace objects, 0(0B) LOS objects, 27% free, 10MB/14MB, paused 1.481ms total 682.547ms
04-17 15:11:45.938: I/Choreographer(1279): Skipped 315 frames!  The application may be doing too much work on its main thread.
04-17 15:11:48.138: I/Choreographer(1279): Skipped 98 frames!  The application may be doing too much work on its main thread.
04-17 15:11:50.785: I/Choreographer(1279): Skipped 92 frames!  The application may be doing too much work on its main thread.
04-17 15:11:52.693: I/Choreographer(1279): Skipped 192 frames!  The application may be doing too much work on its main thread.
04-17 15:11:52.699: I/Process(1279): Sending signal. PID: 1279 SIG: 9

==================================================

@Edit

Now it’s starting to go wrong on that line:

        imgBt.post(new Runnable() {
            imgBt.setBackgroundResource(buttonSelect);
        });

Print:

inserir a descrição da imagem aqui

===========================================================

@Edit

I solved the problem like this:

        imgBt.post(new Runnable() {                 
            @Override
            public void run() {
                imgBt.setBackgroundResource(buttonSelect);
            }
        });

Vlw for the help!

  • I edited my answer.

2 answers

2


Instead of an array with the name of the images declare one with the Resource Id of the images:

int[] varButtonImages = {
    R.drawable.button_blue,
    R.drawable.button_grenn,
    R.drawable.button_red,
    R.drawable.button_yeollow
};

Do the drawing of the image:

final int buttonSelect = varButtonImages[new Random().nextInt(varButtonImages.length)];

Doing so can use the value of buttonSelect in the setBackgroundResource.

findViewById(R.id.ImageSelectGame).setBackgroundResource(buttonSelect);

You should also pass the previous line into the method Run() of TimerTask() for a new image to be selected every 500ms.

Edit after your commission

Of course your code will fail: it tries to update a View out of UI thread
To solve this problem do so:

    final ImageButton imgBt = (ImageButton)findViewById(R.id.ImageSelectGame);
    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            int numberStart = 0;
            int q = 5;

            int buttonSelect = varButtonImages[new Random().nextInt(varButtonImages.length)];

            imgBt.post(new Runnable() {
                @Override
                public void run() {
                    imgBt.setBackgroundResource(buttonSelect);
                }
            });
        }
    }, delay, interval);
  • the application closes when I open the class..

  • Pole the log error.

  • I edited my answer.

  • Look at the new mistake.

  • Click with the right mouse button on top of the word Runnable and do your import. Do buttonSelect final

  • ramral, solved the problem... Voce gave me the wrong function.. I will edit the answer with the solution

  • You’re right, my distraction. Edited answer.

Show 2 more comments

0

You can identify the ids of each drawable and pass them as parameter in your method setBackgroundResource(). For this, use the following code:

int id = getResources().getIdentifier("nome_do_drawable", "drawable", this.getPackageName());

Drawable drawable = getResources().getDrawable(id);

findViewById(R.id.ImageSelectGame).setBackgroundResource(drawable);

OBS.: The parameter "drawable" in the getIdentifier() should not be changed as it represents the type of file that will be searched.

  • Could not, error in "this.getPackageName()"

  • You could post error?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.