通过点击ImageView在Android上生成随机图像

时间:2015-11-23 15:03:03

标签: java android image random

我是Android开发人员的新手,我试图创建一个随机选择3张图片的应用,并在点按图片时在手机屏幕上显示其中一张图片。

问题是图像始终是相同的,而不是改变它消失,并在每次点击时重新出现。

图像名称为:w0.png,w1.png和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);
    }
}

这是activity_main.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="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>

0 个答案:

没有答案