我们想要达到的预期效果图:
.java文件:
package com.example.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class HelloWorld extends AppCompatActivity implements View.OnClickListener{
private Button lastimg;
private Button nextimg;
private ImageView img;
private TextView textView;
private int[] p = {R.drawable.a, R.drawable.b, R.drawable.c,R.drawable.d, R.drawable.e};
private int Index = 0; //图片的当前索引位置
private int count = p.length-1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_world);
init();
}
private void init() {
lastimg = (Button) findViewById(R.id.lastimg);
lastimg.setOnClickListener(this);
nextimg = (Button)findViewById(R.id.nextimg);
nextimg.setOnClickListener(this);
img =(ImageView) findViewById(R.id.img);
textView=(TextView)findViewById(R.id.textView);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.lastimg:
//如果当前图片是第一张,则上一张图片为最后一张图片
if (Index == 0) {
Index = count;
} else {
//否则改为上一张图片索引
Index = Index - 1;
}
break;
case R.id.nextimg:
//如果当前图片是最后一张,则下一张图片为第一张图片
if (Index == count) {
Index = 0;
} else {
//否则改为下一张图片索引
Index = Index + 1;
}
break;
default:
break;
}
img.setImageResource(p[Index]); //显示图片
textView.setText(Integer.toString(Index+1)+"/"+p.length); //显示图片是第几张
}
}
作者:浅殇忆流年