如何在布局xml中拉随机图像?

时间:2013-07-04 22:08:37

标签: android xml android-layout android-drawable

在我的布局xml文件中,我希望'android:src =“”'从drawable中的'bg'文件夹中提取随机图像。

我知道这可以用实际的方式完成,但我想将它保留在布局文件中。

有没有办法在bg文件夹中创建所有内容的数组并从布局xml中拉出来?

1 个答案:

答案 0 :(得分:1)

简短回答是否定的,但我可以提供源代码来帮助以编程方式进行操作

编辑:您需要将您想要使用的所有图像放在drawables文件夹中,然后在bg.xml中放置您想要出现在按钮中的图像,请参阅下面的例子,goodluck!

MainActivity.java

package com.example.stackoverflow17462606;

import java.util.Random;

import android.os.Bundle;
import android.app.Activity;
import android.content.res.TypedArray;
import android.view.Menu;
import android.widget.ImageView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imageView = (ImageView) findViewById(R.id.imageView);
        imageView.setImageResource(getRandomImage());
    }

    private int getRandomImage() {
        TypedArray imgs = getResources().obtainTypedArray(R.array.random_imgs);
        // or set you ImageView's resource to the id
        int id = imgs.getResourceId(new Random().nextInt(imgs.length()), -1); //-1 is default if nothing is found (we don't care)
        imgs.recycle();
        return id;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

bg.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
       <string-array name="random_imgs">
        <item>@drawable/ic_launcher</item>
        <item>@drawable/ic_settings</item>
        <!-- ... -->
    </string-array>

</resources>

activity_main.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/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"/>

</RelativeLayout>