<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <ImageButton
        android:id="@+id/imgbtn"
        android:contentDescription="@string/img_desc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/bg_star_icon" /> //放在drawable資料夾底下的bg_start_icon.png,為一開始的預設圖(?)

</RelativeLayout>



package com.lcpan.imagebutton;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageButton imgbtn;
    private int click=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgbtn = (ImageButton)findViewById(R.id.imgbtn);
        imgbtn.setOnClickListener(this);
    }

    public void onClick(View v) {
        Bitmap img;
      if(click%2==0)
        img = BitmapFactory.decodeResource(getResources(), R.drawable.bg_moon_icon);
          decodeResource(Resources res, int id)

                  Synonym for decodeResource(Resources, int, android.graphics.BitmapFactory.Options) with null Options.

                 getResources()把所有R.java中的設定都抓出來,後面的int是用以抓特定對象的索引值

    else
         img = BitmapFactory.decodeResource(getResources(), R.drawable.bg_star_icon);

        click++;
        imgbtn.setImageBitmap(img);
        //把從R.java中拿到的圖片放到按鈕上
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
創作者介紹

學習筆記專區

乙方 發表在 痞客邦 PIXNET 留言(0) 人氣()