본문 바로가기

JAVA/안드로이드 프로그래밍

Android Studio를 활용한 안드로이드 프로그래밍 연습문제 321p 4번 문제

MainActivity.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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <ImageView
        android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        />

</LinearLayout>

JAVA

package com.example.a321p4;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    ImageView img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView) findViewById(R.id.img1);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
      super.onCreateOptionsMenu(menu);
        MenuInflater mInflater = getMenuInflater();
        mInflater.inflate(R.menu.menuoption,menu);
      return  true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.op1:
                img.setImageResource(R.drawable.ic_launcher_background);
                break;
            case R.id.op2:
                img.setImageResource(R.drawable.ic_launcher_foreground);
                break;
            case R.id.op3:
                img.setImageResource(R.mipmap.ic_launcher);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

 

MenuOption.XML

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/op1"
    android:title="개"
    ></item>
    <item
        android:id="@+id/op2"
        android:title="고양이"
        ></item>
    <item
        android:id="@+id/op3"
        android:title="토끼"
        ></item>

</menu>