天天看點

圖像按鈕ImageButton和圖像ImageView

在AndroidApp應用中,圖像是必不可少的。我們可以通過圖像ImageView來展示。

一、設計界面

  1、首先把a.jpg、b.jpg、c.jpg、d.jpg、e.jpg、prov.png、next.png圖檔複制到res/drawable-hdpi檔案夾内。

圖像按鈕ImageButton和圖像ImageView

2、打開“res/layout/activity_main.xml”檔案,生成ImageButton按鈕。

  (1)從工具欄向activity拖出1個圖像ImageView、2個圖像按鈕ImageButton。該控件來自Image&Media。

圖像按鈕ImageButton和圖像ImageView

3、打開activity_main.xml檔案。

  我們把自動生成的代碼修改成如下代碼,具體為:

   (1)ImageView的id修改為picture;

  (2)“上一幅”按鈕ImageButton的id修改為prov;

  (3)設定android:padding="0dp",按鈕灰色邊框去掉。

    (4)“下一幅”按鈕ImageButton的id修改為next;

  (5)設定android:padding="0dp",按鈕灰色邊框去掉。

<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:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity" >

    <ImageButton

        android:id="@+id/prov"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentBottom="true"

        android:layout_alignParentLeft="true"

        android:layout_marginBottom="99dp"

        android:layout_marginLeft="28dp"

        android:src="@drawable/prov" 

        android:padding="0dp"/>

        android:id="@+id/next"

        android:layout_alignTop="@+id/prov"

        android:layout_marginLeft="79dp"

        android:layout_toRightOf="@+id/prov"

        android:src="@drawable/next" 

    <ImageView

        android:id="@+id/picture"

        android:layout_above="@+id/prov"

        android:layout_centerHorizontal="true"

        android:layout_marginBottom="101dp"

        android:src="@drawable/a" />

</RelativeLayout>

二、單擊事件 

  打開“src/com.genwoxue.ImageView/MainActivity.java”檔案。

  然後輸入以下代碼:

圖像按鈕ImageButton和圖像ImageView

在以上代碼中,我們着重分析一下帶有淺藍色背景部分。

  1、第①部分

  導入與ImageView、ImageButton相關的包。

  2、第②部分

  聲明ImageView、ImageButton控件變量。

  3、第③部分

  聲明整型數組iImages用于存儲圖檔資源。

  4、第④部分

  (1)findViewById()方法完成ImageView、ImageButton控件的捕獲。

  (2)“上一幅”、“下一幅”按鈕添加單擊監聽事件:ibtnProv.setOnClickListener(new ProvOnClickListener())、ibtnNext.setOnClickListener(new NextOnClickListener())。

  5、第⑤部分

  (1)我們建立一個類ProvOnClickListener繼承接口OnClickListener用以實作單擊事件監聽。

  (2)單擊按鈕能夠顯示上一幅圖檔,如果到頭了,則重置到最後一幅。

  6、第⑥部分

  (1)我們建立一個類NextOnClickListener繼承接口OnClickListener用以實作單擊事件監聽。

  (2)單擊按鈕能夠顯示下一幅圖檔,如果到頭了,則重置到第一幅。

直接寫成匿名内部類也行: