【问题标题】:Random Image Generation on Android by tapping on ImageView通过点击 ImageView 在 Android 上随机生成图像
【发布时间】:2015-11-23 15:03:03
【问题描述】:

我是 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>

【问题讨论】:

  • nextInt(2) 返回 0 或 1。您可能想要 nextInt(3)

标签: java android image random


【解决方案1】:

我认为您的问题来自于您在 Activity 的整个生命周期中使用相同的 Random() 实例。 Java 的Random 是一个伪随机数生成器,这意味着您可以多次获得相同的值。当您实例化 rgenerator 时,它将具有相同的种子,并将使用它来生成您的 random 值。

您还使用.nextInt(int n),根据定义排除值n,在您的情况下为值2,这意味着您只剩下要返回的值01。从文档来看,您在指定的时间间隔内获得任何值的机会几乎相同,因此在您的情况下,您确实有平等的机会获得01,因为只有两个值。

因为您仅使用Random 来获取三个值之一,我建议您通过在您的范围内使用增量或其他简单方法来创建随机化。

您可以在官方文档here 中阅读有关Java Random 类的更多信息以及如何使用它的小示例here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2013-02-16
    • 2013-02-28
    • 2020-07-02
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多