安卓编程实现单机按钮改变屏幕蓝色变红色,具体代码
时间: 2024-05-11 15:17:35 浏览: 6
可以使用以下代码实现单机按钮改变屏幕蓝色变红色的效果:
XML布局文件:
```
<Button
android:id="@+id/btn_change_color"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="改变颜色"
android:onClick="changeColor" />
<View
android:id="@+id/view_color"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/blue" />
```
Java代码:
```
public class MainActivity extends AppCompatActivity {
private View mViewColor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewColor = findViewById(R.id.view_color);
}
public void changeColor(View view) {
mViewColor.setBackgroundColor(getResources().getColor(R.color.red));
}
}
```
以上代码实现了一个按钮和一个视图,当点击按钮时,会将视图的背景色从蓝色改变为红色。其中,按钮使用了 `android:onClick` 属性,指定了点击事件的处理函数。点击事件处理函数中调用 `setBackgroundColor()` 方法改变视图的背景色。