작동 과정
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="563dp"
app:srcCompat="@drawable/boy_img" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Color1"
/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Color2" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Color3" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Color4" />
</LinearLayout>
</LinearLayout>
JAVA
package com.example.a05_13;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
Button button1, button2, button3, button4;
ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
iv = (ImageView) findViewById(R.id.imageView);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
iv.setBackgroundColor(Color.RED);
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
iv.setBackgroundColor(Color.BLUE);
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
iv.setBackgroundColor(Color.GREEN);
}
});
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
iv.setBackgroundColor(Color.YELLOW);
}
});
}
}