Search code examples
androidrandomandroid-imageandroid-button

Application when the button is pressed it random picks image from drawable folder


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>

--


Solution

  • 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