본문 바로가기
App/Android Studio

Android Studio - 버튼 클릭 시 ImageView 동적 변경

by 코젼 2022. 8. 4.
728x90
반응형

2022-08-04(33일차)


📃IMAGE CHANGE 버튼을 누르면 ImageView의 사진이 바뀌게 하시오


📝layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp">

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:backgroundTint="#ff9999"
        android:text="Image Change"
        android:textSize="30dp" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/iv"/>
</LinearLayout>

📝MainActivity.java

package com.example.clicklistener;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);

        btn = findViewById(R.id.btn);
        btn.setOnClickListener(lis);

        ImageView iv = findViewById(R.id.iv);
        iv.setBackgroundResource(R.drawable.house);
    }

    View.OnClickListener lis = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageView iv = findViewById(R.id.iv);
            iv.setBackgroundResource(R.drawable.cat);
        }
    };
}

 

728x90
반응형

댓글