Android 關於簡單圖片瀏覽器的實現
介面設計: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:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvShow"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/Hello_word"
android:textSize="20sp"/>
<ImageView
android:id="@+id/ivShow"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="center"
android:src="@mipmap/image1"/>
<LinearLayout
android:id="@+id/linerl"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:orientation="horizontal">
<ImageButton
android:id="@+id/btnLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="25dp"
android:src="@mipmap/btn_pre_gray" />
<ImageButton
android:id="@+id/btnRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="90dp"
android:src="@mipmap/btn_next_gray" />
</LinearLayout>
</LinearLayout>
JAVA程式碼頁面
package com.example.dell.imagetest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView tvShow; ImageButton btnLeft,btnRight; ImageView ivShow; int currentimageid=0; //記錄當前圖片顯示的ID int imageid[]={R.mipmap.image1,R.mipmap.image2,R.mipmap.image3,R.mipmap.image4};//建立一個數組 裡面放的是圖片ID @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvShow=(TextView)findViewById(R.id.tvShow); btnLeft=(ImageButton) findViewById(R.id.btnLeft); btnRight=(ImageButton) findViewById(R.id.btnRight); ivShow=(ImageView)findViewById(R.id.ivShow); btnRight.setOnClickListener(new Action()); btnLeft.setOnClickListener(new Action()); } class Action implements View.OnClickListener{ @Override public void onClick(View v) { if (v==btnLeft){ //如果單擊的是上一張按鈕 currentimageid=(currentimageid-1+imageid.length)%imageid.length;//計算圖片在陣列的中id ivShow.setImageResource(imageid[currentimageid]);//設定顯示的圖片 } if (v==btnRight){ currentimageid=(currentimageid+1+imageid.length)%imageid.length; ivShow.setImageResource(imageid[currentimageid]); } } } }