【问题标题】:Android ImageView program, how to set imageview according to random functionAndroid ImageView程序,如何根据随机函数设置imageview
【发布时间】:2018-06-29 03:18:23
【问题描述】:

假设我有 200 张图片,图片的名称是:

  • 图像1
  • 图像2
  • .
  • .
  • .
  • image200

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

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

【问题讨论】:

    标签: android imageview logic


    【解决方案1】:

    尝试以下操作:(假设您的图像存储在 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多