Java Android Studio:如何将背景更改为 jpg。使用 OnclickListener 的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24398569/
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-14 11:58:46  来源:igfitidea点击:

Android Studio: How to change the Background to jpg. images using OnclickListener

javaandroidandroid-layoutandroid-intent

提问by zuludictator

So far I know how to change the Background's color via html codes. Now I am Trying to change the background of the Layout of my main activity to different images using a button click. If possible using only one single button.

到目前为止,我知道如何通过 html 代码更改背景的颜色。现在我正在尝试使用单击按钮将我的主要活动布局的背景更改为不同的图像。如果可能,只使用一个按钮。

Thank you!

谢谢!

回答by Anil Jadhav

Try below code

试试下面的代码

main.xml

主文件

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/myLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="64dp"
        android:layout_marginTop="71dp"
        android:text="changeColor" />

  </LinearLayout>

MainActivity.java

主活动.java

public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button button;
LinearLayout mainLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mainLayout=(LinearLayout)findViewById(R.id.myLayout);
    button=(Button)findViewById(R.id.button1);
    button.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
        // TODO Auto-generated method stub
         mainLayout.setBackgroundResource(R.drawable.newImage);

    }
});
}
}

回答by user3331142

The following code is from this link Setting background image in javafrom Omi0301.

以下代码来自此链接Omi0301 的java 中设置背景图像

//assuming your Layout is named linearlayout1:
 LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout1);
 ll.setBackgroundResource(R.drawable.sample);

All you do is create a layout variable and set its background resource with the image that you would like it to be.

您所做的就是创建一个布局变量并使用您希望的图像设置其背景资源。

回答by jafika

try to use "setImageResource" instead the "setBackgroundResourse"

尝试使用“setImageResource”而不是“setBackgroundResourse”