Random Image Generation on Android by tapping on ImageView

Random Image Generation on Android by tapping on ImageView

By : tonymu
Date : November 21 2020, 09:01 AM
Hope this helps I think your problem comes from the fact that you use the same instance of Random() over the lifetime of your Activity. Java's Random is a pseudo random number generator, meaning that you can get the same values multiple times. When you instantiate rgenerator it will have the same seed and it will use it to generate your random values.
Also you use .nextInt(int n) which by definition excludes value n, in your case value 2, meaning that you are left only with values 0 and 1 to be returned. From documentation, it looks like you get almost equal chances to get any value in the interval specified, so in your case you really have equal chances to get a 0 or a 1 because there are only two values.
code :

Share : facebook icon twitter icon
Android: Circle moves to random location when tapping it

Android: Circle moves to random location when tapping it

By : Fati Zahra
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I am writing a program that draws a circle at a random location on the phone screen. What it is supposed to do is when the circle is touched, it removes that circle and moves it to another random location. , Change the code like this ,
code :
    public boolean onTouchEvent(MotionEvent event) {
        if (isInsideCircle(event.getX(), event.getY())) {
        return super.onTouchEvent(event);

    boolean isInsideCircle(float xPoint, float yPoint) {
        float dx = (x - xPoint);
        float dxPow = (float) Math.pow(dx, 2);
        float dy = (y - yPoint);
        float dyPow = (float) Math.pow(dy, 2);
        float radPow = (float) Math.pow(r, 2);
        return (dxPow + dyPow) < radPow || (dxPow + dyPow == radPow);
Generation of random Image by tapping on imageView

Generation of random Image by tapping on imageView

By : Nash
Date : March 29 2020, 07:55 AM
help you fix your problem I have Modified your code just copy & paste it, your problem was you are creating random no & accessing resource out of onCreate() method
code :
 package com.example.surya.musicpleer;

import android.app.Activity;
import android.graphics.Typeface;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends Activity {

    ImageView i1;
    Random r = new Random();

    public void onCreate(Bundle savedInstanceState) {
        i1 = (ImageView) findViewById(R.id.imageView);
        i1.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                int target = r.nextInt(3);
                String drawablename = "photo" + target;

                int resID = getResources().getIdentifier(drawablename, "drawable", getPackageName());

i1.setTag(resID); // this line is importent 
private int getDrawableId(ImageView iv) {
    return (Integer) iv.getTag();
Android ImageView program, how to set imageview according to random function

Android ImageView program, how to set imageview according to random function

By : Takuya Yokono
Date : March 29 2020, 07:55 AM
this will help Try the following: (Assuming that your images are stored in the drawables folder).
1) MainActivity1.class:---------
code :
public class MainActivity1 extends AppCompatActivity {

private ImageView iv;

protected void onCreate(@Nullable Bundle savedInstanceState) {


    iv = (ImageView) findViewById(R.id.iv);

    // initial

    // onClick generate a different one.
    iv.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {


private void generatePicture(){

    Random r = new Random();
    int i1 = r.nextInt(200) + 1;// generates a number between 1 and 200 including both ends.

    try {
        iv.setImageDrawable(getResources().getDrawable(getResources().getIdentifier("image" + i1, "drawable", getPackageName())));
    }catch (Exception e){
<?xml version="1.0" encoding="utf-8"?>


android ImageView in RecyclerView loads the same image in random positions

android ImageView in RecyclerView loads the same image in random positions

By : Matthew Galpin
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further In your onBindViewHolder where you're loading the image into ImageView use holder.imageView.setImageBitmap(null) like this. This will reset the ImageView and flush previously used Image immediately.
How to add an image to a random ImageView in Android Studio?

How to add an image to a random ImageView in Android Studio?

By : Neto Chavez
Date : March 29 2020, 07:55 AM
this will help Keep IDs of all avaliable ImageViews in single collection in your activity:
code :
private List<Integer> images = new ArrayList<>();

onCreate() {
onClick(View view) {
  int rnd = new Random().nextInt(images.size() - 1);
  int id = images.get(rnd);
Related Posts Related Posts :
  • Failed to find provider info for urbanairship.provider
  • Android ListView Adapter Crash issue/Duplicates
  • Displaying Splash screen only once on user preference
  • Loop List<WebElement> doesn't stop despite no more WebElements
  • Check if pattern exists in a String
  • Swing - Key Problems (Arrow Keys, Tab, etc.) in GUIs with TextComponents
  • Why the solution for binary search tree validity is not working?
  • Double encrypting 2048 RSA?
  • create junit test for runnable class
  • Unable to read and sort information from a text file in Java
  • My device isn't getting detected in android studio (driver issue)
  • Representing a Graph in Java
  • How to XML mapping using jxls
  • Quick Sort stackoverflow error for large arrays
  • Parsing Apache Tika XML Output returns Unknown Tag
  • java simple UI loop, can't find bug
  • how to use greater than and less than in a single if statement in java
  • Error:(27, 13) Failed to resolve: com.antonyt.infiniteviewpager:library:1.0.0
  • Gradle dependencies on source set of different projects
  • Session Scope in Restful Spring Services
  • Java: Change a value in an overridden method of a different class to a value that was calculated in the class
  • Event notification if SWT Combo display list is visible
  • Hibernate WrongClassException for Custom Discriminators
  • User define enum element method in Java? /Hearthstone Text Game/
  • Java Multi-dimensional Array Average
  • Doubly Linked List delete last
  • First time Fragment, and I got "Application has stopped" when I try open it with fragmentTransaction
  • How to model two one-to-one relationships between the same two tables in Hibernate?
  • IntelliJ - include pom.xml dependencies in lib directory
  • Tomcat 7 : Filtering lifecycle events
  • JSONException: Names must be strings
  • Build Spark JavaRDD List from DropResult objects
  • Include css file in richlet with zk
  • Jackson CSV's WRAP_AS_ARRAY
  • Priority for a web request in Java web applications
  • Is there a better way to format this timestamp to ISO8601?
  • Issue with Spring Scope
  • How to declare and use an array of dictionaries from Python in Java and filter them?
  • Wrong weekdays from Calendar.getDisplayName()
  • ClassNotFoundException when creating new ClassPathXmlApplicationContext
  • Java Method Call from Thread
  • Remove background noise from image to make text more clear for OCR
  • PostgreSQL query always return true
  • How to connect FX controller with main app
  • Is there a difference between these two code snippets, and if so what?
  • When two interfaces have conflicting return types, why does one method become default?
  • Updating database throws errors in To Do List app
  • Where does the url come from?
  • Dagger 2 issue overriding single provides annotated method from a module in a library which app uses
  • Better way then If(x instanceof y) in Java?
  • how to debug maven enunciate plugin tomcat web service
  • Spring Context Initialization fails when upgrading to version 4.2.3
  • spring boot cannot connect to rabbitmq
  • How to Run Unit Test in Parallel Across All Modules Using Maven?
  • Getting the next Value in a ArrayList(Not working)
  • How to wait for a MouseListener mouse press?
  • Java RMI: Blocking for void method return?
  • Get Table Properties out of Hive using Java API
  • Read CSV file and write to another CSV - ArrayIndexOutOfBoundsException and pattern difficuties
  • Set LineChart(javafx) style to a child element
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co