【问题标题】:Randomly set background image - Android随机设置背景图片 - Android
【发布时间】:2014-06-26 15:18:24
【问题描述】:

我在登录屏幕上设置了一个背景,我想在每次从我的 drawables 文件夹中的一堆图像加载应用程序时随机设置背景。但是,每次尝试编写代码来执行此操作时,我的应用都会崩溃。

我在 layout/strings.xml 中定义了我的数组:

<?xml version="1.0" encoding="utf-8"?>

<string name="app_name">MyFSU</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>

<style name="DefaultButtonText">
    <item name="android:layout_width">fill_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textColor">#979797</item>
    <item name="android:gravity">center</item>
    <item name="android:layout_margin">3dp</item>
    <item name="android:textStyle">normal</item>
    <item name="android:textSize">20sp</item>
    <item name="android:shadowColor">#f9f9f9</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">1</item>
</style>

<array name="myImages">
   <item>@drawable/a</item>
   <item>@drawable/b</item>
   <item>@drawable/c</item>
   <item>@drawable/d</item>
   <item>@drawable/e</item>
</array>

然后这是我实际生成随机图像的代码:

public class MainActivity extends ActionBarActivity {

final RelativeLayout background = (RelativeLayout) findViewById(R.id.back);
Resources res = getResources();
final TypedArray myImages = res.obtainTypedArray(R.array.myImages);
final Random random = new Random();

public void backgrounds(View v) {
    int randomInt = random.nextInt(myImages.length());
    int drawableID = myImages.getResourceId(randomInt, -1);
    background.setBackgroundResource(drawableID);
}

Logcat 在&lt;init&gt; 处显示空指针异常,但我不知道它在哪里或如何修复它。 :(

有人有什么建议吗?

【问题讨论】:

    标签: android random


    【解决方案1】:

    你应该搬家

    final RelativeLayout background = (RelativeLayout) findViewById(R.id.back);
    Resources res = getResources();
    final TypedArray myImages = res.obtainTypedArray(R.array.myImages);
    

    onCreate 内,在setContentView 之后。 setContentView(int),膨胀并将膨胀的视图放置在 Activity 视图的层次结构中,让您可以在其中查找 R.id.back,就您而言

    【讨论】:

    • 好的,所以,这解决了它。我将与随机背景相关的所有内容移至 onCreate(bundle savedInstanceState) 内部。这似乎解决了它,现在它正在拉随机图片!但是,我时不时会收到 nullpointerexception 和崩溃,但我认为这可能来自损坏的资源......谢谢!
    【解决方案2】:

    我会创建一个采用最小值和最大值的方法:

    伪代码

    public static int generateRandomInt(int min,int max)
        {
            return min + (int)(Math.random() * ((max - min) + 1));
        }
    
    public void backgrounds(View v) {
        int randomInt = generateRandomInt(0,myImages.length()-1);
        int drawableID = myImages.getResourceId(randomInt);
        v.setBackgroundResource(getResources().getDrawable(drawableID)); // assuming your array is of resource ids
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多