dimanche 21 février 2016

Display a random image from array in ImageView

I have an array of strings that displays a random text result in a TextView after a button is pressed and after 5000 milliseconds. What I am trying to achieve is to have an array of images instead of text and so would like a random image showing in an ImageView after the 5000 milliseconds.

public class MainActivity extends AppCompatActivity {
    private ImageView thumbPrint;
    private TextView result;
    private AnimationDrawable thumbAnimation;
    private String[] moodResults;
    private Runnable mRunnable;

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

        moodResults = new String[]{
            "result a",
            "result b",
            "result c",
            "result d",
            "result e",
            "result f"
        };

        thumbPrint = (ImageView)findViewById(R.id.thumbPrint);
        thumbPrint.setBackgroundResource(R.drawable.thumb_animation);
        thumbAnimation = (AnimationDrawable)thumbPrint.getBackground();

        result = (TextView)findViewById(R.id.resultText);

        thumbPrint.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                thumbAnimation.start();
                showResult();
                return true;
            }
        });
    }

    public void showResult(){
        mRunnable = new Runnable() {
            @Override
            public void run() {
                int rand = (int)(Math.random()* moodResults.length);
                result.setText(moodResults[rand]);
                //stop animation
                thumbAnimation.stop();
            }
        };

        Handler mHandler = new Handler();
        mHandler.postDelayed(mRunnable, 5000);
    }
}




Aucun commentaire:

Enregistrer un commentaire