首页 > 解决方案 > Android ImageView程序,如何根据随机函数设置imageview

问题描述

假设我有 200 张图像名称为:

现在我可以使用随机函数生成 1 到 200 的随机数。并且由于所有图像名称都是相同的,除了最后一个数字。我可以将我的图像视图设置为(连接图像和随机数)。

例如,我的随机数生成 20,所以我将连接 image+20,这将给我 image20,然后我想将我的 imageView 设置为 image20。

标签: androidimageviewlogic

解决方案


尝试以下操作:(假设您的图像存储在 drawables 文件夹中)。

1) MainActivity1.class:---------

public class MainActivity1 extends AppCompatActivity {

private ImageView iv;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.layout10);

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

    // initial
    generatePicture();

    // onClick generate a different one.
    iv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            generatePicture();
        }
    });

}

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){
        e.printStackTrace();
    }
}
}

2) layout10.xml:--------

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/iv"/>

</android.support.constraint.ConstraintLayout>

推荐阅读