1.准备好两张图片可以多准备几张我只用了两张
2.activity_main.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"
tools:context=".MainActivity"
android:orientation="horizontal">
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="462dp"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="@drawable/shanshui" />
<Button
android:id="@+id/button_1"
android:layout_width="wrap_content"
android:layout_height="58dp"
android:layout_marginLeft="-350dp"
android:layout_marginTop="500dp"
android:text="上一张" />
<Button
android:id="@+id/button_2"
android:layout_width="wrap_content"
android:layout_height="58dp"
android:layout_marginLeft="88dp"
android:layout_marginTop="500dp"
android:text="下一张" />
</LinearLayout>
3MainActivity代码
package com.example.mymusic;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button button_1,button_2;
ImageView imagView;
int[]photos={R.drawable.shanshui,R.drawable.mamhua};
//显示当前图片索引
private int photoIndex=0;
//图片的索引的最大值
private int maxindex=2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_1=findViewById(R.id.button_1);
button_1.setOnClickListener((View.OnClickListener) this);
button_2=findViewById(R.id.button_2);
button_2.setOnClickListener((View.OnClickListener) this);
imagView=findViewById(R.id.image);
}
@Override
public void onClick(View view){
switch (view.getId()){
case R.id.button_1:
if (photoIndex==0){
photoIndex=maxindex;
}else{
photoIndex=photoIndex -1;
}
break;
case R.id.button_2:
if (photoIndex ==maxindex){
photoIndex =0;
}else{
photoIndex=photoIndex+1;
}
break;
default:
break;
}
imagView.setImageResource(photos[photoIndex]);
}
}