android 开发一个程序,其中某某个按钮嫩根据状态的不同选择不同的图片背景显示。
时间: 2024-02-25 15:58:21 浏览: 18
好的,我会为您提供一个简单的 Android 应用程序示例,实现根据按钮状态选择不同的图片背景显示。
首先,我们需要为应用程序添加两个不同状态的图片资源文件。在这个示例中,我们将分别使用名为 `button_bg_normal.png` 和 `button_bg_pressed.png` 的两个图片资源文件。
接下来,在布局文件中添加一个按钮元素并设置其背景为 `button_bg_normal.png`。同时,在按钮元素中添加一个点击事件监听器,在点击事件处理程序中改变按钮的状态,并根据按钮状态设置按钮的背景。以下是示例布局文件代码:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:background="@drawable/button_bg_normal"
android:layout_centerInParent="true"/>
</RelativeLayout>
```
接下来,在 Activity 类中获取按钮元素,并为其添加一个点击事件监听器。当按钮被点击时,我们将根据按钮当前的状态设置其背景。以下是示例代码:
```java
public class MainActivity extends AppCompatActivity {
private Button mButton;
private boolean mButtonPressed = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mButtonPressed = !mButtonPressed;
if (mButtonPressed) {
mButton.setBackgroundResource(R.drawable.button_bg_pressed);
} else {
mButton.setBackgroundResource(R.drawable.button_bg_normal);
}
}
});
}
}
```
在这个示例中,我们使用一个布尔值 `mButtonPressed` 来保存按钮的状态。当按钮被点击时,我们将其状态取反,并根据状态设置按钮的背景图片。
这样,我们就完成了一个简单的 Android 应用程序,可以根据按钮状态选择不同的图片背景显示。