1

Galera, estou tentando fazer com que a cada 0,5s uma imagem aleatória da pasta drawable seja setada na minha ImageButton mas estou tendo problemas da maneira que fiz.

Tentei fazer da seguinte maneira: coloquei os seguintes nomes nas imagens da pasta drawable:

button_blue, button_grenn, button_red e button_yeollow

E para setar aleatoriamente tentei usando o seguinte código:

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);
    }
}

Mas ele não aceita essa função aqui:

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

Alguém poderia me ajudar?


@Edit

Depois da ajuda do ramaral passei a receber este erro:

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

Agora começou a dar erro nessa linha:

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

Print:

inserir a descrição da imagem aqui

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

@Edit

Resolvi o problema assim:

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

Vlw pela ajuda!

1
  • Editei a minha resposta.
    – ramaral
    17/04/2015 às 16:09

2 Respostas 2

2

Em vez de um array com o nome das imagens declare um com o resource Id das imagens:

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

Faça o sorteio da imagem:

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

Fazendo assim pode usar o valor de buttonSelect no setBackgroundResource.

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

Deverá também passar a linha anterior para dentro do método Run() do TimerTask() para que uma nova imagem seja selecionada a cada 500ms.

Edit após o seu cometário

É claro que o seu código irá dar erro: ele tenta actualizar uma View fora da UI thread
Para resolver esse problema faça assim:

    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);
7
  • a aplicação fecha quando eu abro a classe..
    – Jeiferson
    17/04/2015 às 15:14
  • Poste o log de erro.
    – ramaral
    17/04/2015 às 15:16
  • Editei a minha resposta.
    – ramaral
    17/04/2015 às 16:15
  • Olha la o novo erro.
    – Jeiferson
    17/04/2015 às 16:52
  • Click com o botão do lado direito do rato em cima da palavra Runnable e faça o seu import. Faça buttonSelect final
    – ramaral
    17/04/2015 às 16:57
0

Você pode identificar os ids de cada drawable e passá-los como parâmetro no seu método setBackgroundResource(). Para isso, utilize o seguinte código:

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

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

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

OBS.: O parâmetro "drawable" no getIdentifier() não deve ser alterado, pois ele representa o tipo de arquivo que será procurado.

2
  • Nao consegui, da erro no "this.getPackageName()"
    – Jeiferson
    17/04/2015 às 3:29
  • Você poderia postar o erro?
    – regmoraes
    17/04/2015 às 15:33

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .