AndroidImageView程序,如何根据随机函数设置imageview
Android ImageView program, how to set imageview according to random function
假设我有 200 张图像,图像名称是:
- 图片1
- 图片2
- .
- .
- .
- image200
现在我可以使用随机函数生成 1 到 200 之间的随机数。由于所有图像名称除了最后一个数字外都是相同的。我可以将图像视图设置为(连接图像和随机数)吗?
例如,我的随机数生成 20,所以我将连接 image+20,这将得到 image20,然后我想将我的 imageView 设置为 image20。
尝试以下操作:(假设您的图像存储在 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>
假设我有 200 张图像,图像名称是:
- 图片1
- 图片2
- .
- .
- .
- image200
现在我可以使用随机函数生成 1 到 200 之间的随机数。由于所有图像名称除了最后一个数字外都是相同的。我可以将图像视图设置为(连接图像和随机数)吗?
例如,我的随机数生成 20,所以我将连接 image+20,这将得到 image20,然后我想将我的 imageView 设置为 image20。
尝试以下操作:(假设您的图像存储在 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>