Android 如何在图像视图上显示随机图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20549705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:01:55  来源:igfitidea点击:

How To Display Random images on image view

androidimageview

提问by Anonymous

Could someone please help me out with a code to randomly display a picture from the my drawings folder? i am new to java so i have no idea how to do it. Any help will be appreciated. My Requirements are:- 1.Display Random image (image should change on each start up) 2.that's all

有人可以帮我提供一个代码来随机显示我的图纸文件夹中的图片吗?我是 Java 新手,所以我不知道该怎么做。任何帮助将不胜感激。我的要求是:- 1.显示随机图像(图像应在每次启动时更改)2.仅此而已

import java.util.Random;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainMenu extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
}

public void openNewActivity(View view) { 
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);//button to open main
}
public void browser(View view) { 
    Intent intent = new Intent(this,Browser.class);
    startActivity(intent);//button to open browser
}


final Random rnd = new Random();

{

    setContentView(R.layout.activity_main_menu);

    final ImageView img = (ImageView) findViewById(R.id.imgRandom);
    // I have 3 images named img_0 to img_2, so...
    final String str = "img_" + rnd.nextInt(9);
    img.setImageDrawable
    (
        getResources().getDrawable(getResourceID(str, "drawable",
            getApplicationContext()))
        );
}

protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
    final int ResourceID =
        ctx.getResources().getIdentifier(resName, resType,
            ctx.getApplicationInfo().packageName);
    if (ResourceID == 0)
    {
        throw new IllegalArgumentException
        (
            "No resource string found with name " + resName
            );
    }
    else
    {
        return ResourceID;
    }


}
}

回答by Phant?maxx

Put some images named img_0 to img_n in your res/drawable folder

将一些名为 img_0 的图像放入 res/drawable 文件夹中的 img_n

Layout (res/layout/rnd_images.xml):

布局(res/layout/rnd_images.xml):

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    >
    <ImageView
        android:id="@+id/imgRandom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
    />
</RelativeLayout>

Code:

代码:

package com.example.app;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;

public class MainActivity
extends Activity
{
    final Random rnd = new Random();

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

        setContentView(R.layout.rnd_images);

        final ImageView img = (ImageView) findViewById(R.id.imgRandom);
        // I have 3 images named img_0 to img_2, so...
        final String str = "img_" + rnd.nextInt(2);
        img.setImageDrawable
        (
            getResources().getDrawable(getResourceID(str, "drawable",
                getApplicationContext()))
            );
    }

    protected final static int getResourceID
    (final String resName, final String resType, final Context ctx)
    {
        final int ResourceID =
            ctx.getResources().getIdentifier(resName, resType,
                ctx.getApplicationInfo().packageName);
        if (ResourceID == 0)
        {
            throw new IllegalArgumentException
            (
                "No resource string found with name " + resName
                );
        }
        else
        {
            return ResourceID;
        }
    }
}

Note that you have to set rnd.nextInt(2) to rnd.nextInt(Max - 1), since rnd starts from 0

请注意,您必须将 rnd.nextInt(2) 设置为 rnd.nextInt(Max - 1),因为 rnd 从 0 开始

[UPDATE]

[更新]

The layout name must match that in setContentView.
So, if you have (why?) this:

布局名称必须与 setContentView 中的名称匹配。
所以,如果你有(为什么?)这个:

setContentView(R.layout.activity_main);

in your MainActivity.java/onCreate, then rename the layout "activity_main.xml"

在 MainActivity.java/onCreate 中,然后重命名布局“activity_main.xml”

OR, better, USE MY CODE AS IS.

或者,更好的是,按原样使用我的代码。

It works without modifications.

它无需修改即可工作。

[UPDATE]

[更新]

Check this line:

检查这一行:

final Random rnd = new Random();

It requires the following import:

它需要以下导入:

import java.util.Random;

My code works as is. I tested it before giving it to you.
Just place my layout in res/layout, the images in res/drawable and the MainActivity.java to replace the default one.

我的代码按原样工作。我在给你之前测试了它。
只需将我的布局放在 res/layout 中,将图像放在 res/drawable 和 MainActivity.java 中以替换默认设置。

Please, notice that the images names MUST be "img_#" where # is a number.
This number must be 0 to (max - 1).

请注意,图像名称必须是“img_#”,其中 # 是一个数字。
此数字必须是 0 到(最大 - 1)。

Or give names like "my_city_#" or whatever.
But then you must update the java code to match these names.

或者给出诸如“my_city_#”之类的名称。
但随后您必须更新 java 代码以匹配这些名称