单击按钮android时随机背景

时间:2013-12-04 11:05:10

标签: android

我只想点击按钮并更改背景图片。这是我的不同代码

array.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="image">
    <item>@drawable/photo</item>
    <item>@drawable/photo1</item>
    <item>@drawable/photo2</item>
    <item>@drawable/photo3</item>
    <item>@drawable/photo4</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_above="@+id/back"
    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"
    android:background="@drawable/photo"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="146dp"
        android:text="Button" />

</RelativeLayout>

这是我的活动代码:

final LinearLayout background = (LinearLayout) findViewById(R.id.back);
    Button button = (Button) findViewById(R.id.button1);
    Resources res = getResources();
    final TypedArray myImages = res.obtainTypedArray(R.array.image);
    final Random random = new Random();

    button.setOnClickListener(new Button.OnClickListener() 
    {

        public void onClick(View v) {

           int randomInt = random.nextInt(myImages.length());
           background.setBackgroundResource(myImages.getResourceId(randomInt,-1));
           int drawableID = myImages.getResourceId(randomInt,-1);
            background.setBackgroundResource(drawableID);

        }

    });

它不起作用,你能帮助我吗? 提前致谢

3 个答案:

答案 0 :(得分:0)

在xml中,您使用的是RelativeLayout,但在活动代码中,您是LinearLayout。

答案 1 :(得分:0)

您在代码中输入了错误的布局。您已将x RelativeLayout放在xml文件中,并将其转换为java文件中的LinearLayout

在您的java文件中,将LinearLayout更改为RelativeLayout

final LinearLayout background = (LinearLayout) findViewById(R.id.back);

写下这个:

 final RelativeLayout background = (RelativeLayout) findViewById(R.id.back);

答案 2 :(得分:0)

如果案例不是LinearLayout,请执行以下操作:

将数组的定义更改为

final String[] myImages = res.getStringArray(R.array.image);

然后,替换你的onClick方法:

public void onClick(View v) {

       int randomInt = random.nextInt(myImages.length);
       int drawableID = myImages.getResources().getIdentifier(myImages[randomInt], "drawable", this.getPackageName());
       background.setBackgroundResource(drawableID);

   }