【问题标题】:Change Background Image of RelativeLayout from within Java Class (Android App)从 Java 类(Android 应用程序)中更改 RelativeLayout 的背景图像
【发布时间】:2013-07-22 22:51:43
【问题描述】:

所以我正在使用 Android 4.0 库开发一个 Android 应用程序。

此应用程序的一个活动由具有图像背景和切换按钮的 RelativeLayout 组成。 当用户切换按钮时,布局的背景图像必须改变。

所以必须从activity.java类内部改变:

if (toggleButton.isChecked()){

// Change the background of the activity to image 2 (for example)           
 }

else{ // when toggle button is off

// Change it back to image 1

}

请帮我解决这个问题。谢谢你:)

【问题讨论】:

    标签: java android xml android-layout


    【解决方案1】:

    您在View 类中使用setBackground 方法:

    if (toggleButton.isChecked()){
    
    // Change the background of the activity to image 2 (for example) 
    View myView =  this.findViewById(yourViewId); 
    myView.setBackgroundResource(yourImage);         
     }
    
    else{ // when toggle button is off
    
    // Change it back to image 1
    // Change the background of the activity to image 2 (for example) 
     View myView =  this.findViewById(yourViewId); 
    myView.setBackgroundResource(yourOtherImage);
    }
    

    【讨论】:

    • 谢谢,这很有帮助。但是,它并没有那样工作。不知何故,活动拒绝使用 setBackground() 方法。
    • 我使用了以下内容:Integer[] images = { R.drawable.image0, R.drawable.image1 };然后: if (toggle.isChecked()){ myView.setBackgroundResource(images[0]); } else{ myView.setBackgroundResource(images[1]);这对我有用:)
    猜你喜欢
    • 1970-01-01
    • 2015-07-18
    • 2011-10-11
    • 2012-07-14
    • 2016-04-29
    • 2016-09-06
    • 2012-12-25
    • 2015-06-26
    • 2016-06-09
    相关资源
    最近更新 更多