显示来自,, drawable"的随机图像Android中的文件夹

时间:2017-05-15 15:52:12

标签: java android random

package com.example.paul_2.a5mai;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        start();


    }
    void start () {

//root layout
        LinearLayout root = new LinearLayout(this);
        root.setOrientation(LinearLayout.VERTICAL);
        root.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
        setContentView(root);

//butonul de start
        Button StartBTN = new Button(this);
        StartBTN.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
        StartBTN.setText("Click Me");
        root.addView(StartBTN);


// contine toate cele 5 layouturi
        final LinearLayout linearContainer=new LinearLayout(this);
        linearContainer.setOrientation(LinearLayout.HORIZONTAL);
        linearContainer.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
        root.addView(linearContainer);

//LINIA 1
        final LinearLayout firstRow = new LinearLayout(this);
        firstRow.setOrientation(LinearLayout.VERTICAL);
        firstRow.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.MATCH_PARENT));
        linearContainer.addView(firstRow);

        //dimensiunea imaginii
        RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(200,200);
        //params1.leftMargin =10;
        //params1.topMargin = 10;

        //final ImageView cherry = new ImageView(this);
        //cherry.setBackgroundResource(R.drawable.cherry1);
        //firstRow.addView(cherry,params1);

        final ImageView imgView = new ImageView(this);
        Random rand = new Random();
        int rndInt = rand.nextInt(n) + 1; // n = the number of images, that start at idx 1
        String imgName = "img" + rndInt;
        int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
        imgView.setImageResource(id);
        firstRow.addView(imgView, params1);
    }
}

我需要帮助,了解我应该做什么才能展示" imgView"从3个不同的图像中随机抽取" drawable"夹。首先,我不知道我应该在String imgName =?之后写。其次,rndInt的值必须是3,我的意思是n = 3? (如果我有3张图片保存在" drawable"文件夹。请有人帮我这个,因为我需要这个用于学校。提前谢谢!

0 个答案:

没有答案