简体   繁体   English

单击按钮时将布局背景更改为其他图像

[英]change background of layout to anoher image when clicking a button

when i want to change background image to another image i can't 当我想将背景图像更改为另一幅图像时,我无法

btn = (Button)findViewById(R.id.button1);

btn.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        relativeLayout.setBackgroundResource(R.drawable.bbbn);
    }
});

What is the problem or error you getting? 您遇到的问题或错误是什么? You should describe your problem and errors as well. 您还应该描述您的问题和错误。

It is very simple, It seems you want to change the background image of a relative layout on button click. 这很简单,似乎您想在单击按钮时更改相对布局的背景图像。

Here is the activity layout 这是活动布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent" >

<Button
    android:id="@+id/btn"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Button" >
</Button>

<RelativeLayout
    android:id="@+id/rl"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_below="@+id/btn"
    android:background="@drawable/default_image_name" >
</RelativeLayout>

</RelativeLayout>

Here is the code for activity 这是活动代码

public class MainActivity extends Activity {

Button button;
RelativeLayout layout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_main);
    button = (Button) findViewById(R.id.btn);
    layout = (RelativeLayout) findViewById(R.id.rl);

    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            // Give image name that you want to show on button click
            layout.setBackgroundResource(R.drawable.second_image_name);
        }
    });
}
}

Note: Put images on mdpi folder also. 注意:也将图像放在mdpi文件夹中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM