lundi 23 novembre 2015

Random Image Generation on Android by tapping on ImageView

I'm pretty new to Android developing and I'm trying to make an app that chooses between 3 images randomly and shows one of them on the phone screen whenever the image is tapped.

The problem is that the image is always the same and instead of changing it disappears and reappears with every tap.

The images names are: w0.png, w1.png and w2.png

private static final Random rgenerator = new Random();
private ImageView iv;
private int q;

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

    q = rgenerator.nextInt(2);
    iv = (ImageView) findViewById(R.id.imageView1);
    int resId = getResources().getIdentifier("w"+q, "drawable", getPackageName());
    iv.setImageResource(resId);

    iv.setOnClickListener(this);
}


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


@Override
public void onClick(View v) {
    if(v.getId()==R.id.imageView1)
    {
        int resId = getResources().getIdentifier("w"+ rgenerator.nextInt(2), "drawable", getPackageName());
        iv.setImageResource(resId);
    }
}

This is activity_main.xml

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
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="com.example.mandandroid.MainActivity" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="100px"
    android:layout_height="100px"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"/>
</RelativeLayout>




Aucun commentaire:

Enregistrer un commentaire