2

I am new in Android development, and I've looked around for few codes to combine, but with no luck..

So I want to create an Android Application, when the button is pressed, it random picks image from drawable folder, and you can't press button again for 30 secs.

Any help would be welcome.

Randomactivity.java

package com.example.no;

import java.util.Random;

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.ImageView; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.view.View.OnClickListener; 

public class RandomImage extends Activity implements OnClickListener{ 
    private static final Random rgenerator = new Random(); 
    Integer [] mImageIds = { 
            R.drawable.img1, 
            R.drawable.img2, 
            R.drawable.img3, 
            }; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)]; 
    ImageView iv = (ImageView) findViewById(R.id.imageviewyeah); 
    iv.setTag(q); 
    View nextButton = findViewById(R.id.next_image_button); 
    nextButton.setOnClickListener(this); 
} 

    @Override 
    public void onClick(View v) { 
    switch (v.getId()) { 
    case R.id.next_image_button: 
        Intent i = new Intent(this, RandomImage.class); 
        startActivity(i); 
        break; 
    } 
} 

    @Override 
        public boolean onCreateOptionsMenu (Menu menu) { 
                super.onCreateOptionsMenu(menu); 
                MenuInflater inflater = getMenuInflater(); 
                inflater.inflate(R.menu.main, menu); 
                return true; 
        } 
@Override 
public boolean onOptionsItemSelected (MenuItem item) { 
                switch (item.getItemId()) { 
                case R.id.action_settings: 
                        startActivity(new Intent(this, MainActivity.class)); 
                        return true; 
} 

return false; 
        } 

}

-- activity_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    android:orientation="vertical" 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/widget0" 
android:background="@drawable/bgi" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
    android:layout_gravity="center" > 
<ImageView 
        android:id="@+id/imageviewyeah" 
        android:tag="q" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_gravity="center"> 
</ImageView> 
<Button 
        android:id="@+id/next_image_button" 
        android:text="Next Image" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:padding="10dip" 
        android:typeface="serif"/> 
</LinearLayout>

--

GrayFox
  • 63
  • 9

3 Answers3

1

In declarations:

final Random rnd = new Random();
ImageView img = null;
Button btnRandom = null;

In Main Activity:

@Override
protected void onCreate(
    final Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    setContentView(R.layout.rnd_images);
    img = (ImageView) findViewById(R.id.imgRandom);
    btnRandom = (Button) findViewById(R.id.btnRandom);
}

protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
    final int ResourceID =
        ctx.getResources().getIdentifier(resName, resType,
            ctx.getApplicationInfo().packageName);
    if (ResourceID == 0)
    {
        throw new IllegalArgumentException
        (
            "No resource string found with name " + resName
            );
    }
    else
    {
        return ResourceID;
    }
}

public void clickHandler(final View v)
{
    switch(v.getId())
    {
        case R.id.btnRandom:
        {
            if (!btnRandom.isEnabled())
            {
                return;
            }

            // I have 3 images named img_0 to img_2, so...
            final String str = "img_" + rnd.nextInt(2);
            img.setImageDrawable
            (
                getResources().getDrawable(getResourceID(str, "drawable",
                    getApplicationContext()))
            );
            btnRandom.setEnabled(false);

            new CountDownTimer(5000, 1000) // Wait 5 secs, tick every 1 sec
            {
                @Override
                public final void onTick(final long millisUntilFinished)
                {
                    btnRandom.setText("Wait: " + (millisUntilFinished / 1000));
                }
                @Override
                public final void onFinish()
                {
                    btnRandom.setText("Change!");
                    btnRandom.setEnabled(true);
                }
            }.start();

            break;
        }
    }
}

The layout (rnd_images.xml)

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    >
    <ImageView
        android:id="@+id/imgRandom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
    />
    <Button
        android:id="@+id/btnRandom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Change!"
        android:onClick="clickHandler"
    />
</RelativeLayout>

[EDIT]

I modified the button definition in layout. And I saw that the timing is not respected, so, I'm going to fix it.

I also fixed the code to properly handle the timing.

[RE-EDIT]

I modified the clickHandler function to show the remaining grace period and fire the first time without any delay after click

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • Only tried this one so far, but it gives me white screen when started with button on down left corner on screen that does nothing.. Will try tommorow with some fixes.. – GrayFox Dec 21 '13 at 00:43
  • Did you put **img_0**, ..., **img_(total-1)** in your res/drawable folder? total-1 is (obviously) the toal number of your images-1 – Phantômaxx Dec 21 '13 at 08:00
  • I fixed my code and my layout. Now it's working - the timing section didn't let it work properly. – Phantômaxx Dec 21 '13 at 08:27
  • Thank you very much Klaus66, it works great , but I have a another proposal for you if you have time.. I want to show how many seconds are left until you can change again to next image.. And another thing of it is possible, that for your first image you dont have to wait , only for other images.. so you open app , click change for the first time(no waiting), then image displays and then you have to wait (lets say 5 secs) to switch again.. – GrayFox Dec 21 '13 at 12:00
  • OK, done. I changed the clickHandler function to work as per your requirements - nice! – Phantômaxx Dec 21 '13 at 12:31
0

Well, the only thing that I could think of is:

1) Get all resources from drawable directory and put them into an array or list

2) Have a random generator number and use that as an index to pick one of the images from the array / list

To get all resources, you might need to find a way to do it. Looked around for a bit and this might help: Android: retrieving all Drawable resources from Resources object

Once you have a List that contains all those resources, you will need to tackle the logic that you want.

Use this to generate your random number: How do I generate random integers within a specific range in Java?

Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
  public void onClick() {
    // assume you put all resources into `resourcesList`
    // `randInt` is the method from the link I gave you
    resourcesList.get(randInt(0, listSize));

    btn.setEnabled(false);
    new AsyncTask<Void, Void, Void>() {
      @Override
      protected Void doInBackground(Void... params) {
        Thread.sleep(30000); // you might need to wrap this with try and catch
        return null;
      }

      @Override
      protected void onPostExecute(Void res) {
        btn.setEnabled(true);
      }
    }.execute();
  }
});

Another way to do this is to use handler.postDelayed.

Handler h = new Handler();
btn.setOnClickListener(...
  public void onClick() {
    btn.setEnabled(false);
    h.postDelayed(new Runnable() {
      @Override
      public void run() {
        // no need to wrap this in `runOnUiThread` if you create do
        // `Handler h = new Handler()` inside a UI thread
        btn.setEnabled(true);
      }
    }, 30000);
  }
);

P.S. AsyncTask might create memory leak: Android: Memory leak due to AsyncTask. Not sure about Handler, you gotta do some research about it

Community
  • 1
  • 1
Ardo K
  • 191
  • 10
0
  1. You should change images names as well your array of drawable(Both of parameter one thing should be common like numeric value so you can easily change image)
  2. Then get value which generate from Random number
QuokMoon
  • 4,387
  • 4
  • 26
  • 50