android - Android ImageView程序,如何根据随机函数设置imageview
问题描述
假设我有 200 张图像名称为:
- 图像1
- 图2
- .
- .
- .
- 图像200
现在我可以使用随机函数生成 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>
推荐阅读
- python - 编写一个循环,将遍历项目列表并仅输出字符串中包含字母的项目
- zerobrane - ZeroBrane 和 LuaJIT FFI
- python - pandas 函数在多级索引表中查找不同索引级别的列总和
- git - 如何将一个分支的更改移植到另一个分支
- python - 我不断收到这个 AttributeError: '_tkinter.tkapp' 对象没有属性 'TK'
- python - PyQGIS在导入csv时更改底图crs
- google-cloud-platform - 如何将项目链接到链接到不同帐户的 GCP 积分?
- java - 如何在spring rest控制器中获取发件人的uri?
- c# - 您好,我想知道这种条件语句是什么意思?if (i == 0) 最低 = 最高 = 输入;
- python - 无法将正确的格式应用于熊猫日期框