上一篇講到ImageView,這篇利用Button切換ImageView的圖片,
可以讓圖片跳至上一張及下一張。
首先在xml檔新增ImageView及切換上下張圖片的2個Button
接著把要切換的圖片放置於專案名稱\app\src\main\res\drawable裡
在imageView裡先放第一張顯示的圖
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" >
<ImageView
android:id="@+id/imageView"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_marginTop="50dp"
android:layout_gravity="center"
app:srcCompat="@drawable/lisa1" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/buttonup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_weight="1"
android:text="上一張圖片" />
<Button
android:id="@+id/buttonnext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="下一張圖片" />
</LinearLayout>
</LinearLayout>
接著到MainActivity.java來設定Button切換imageView的圖片
public class MainActivity extends AppCompatActivity {
Button buttonup;
Button buttonnext;
ImageView imageView;
private int[] picture = {R.drawable.lisa1,R.drawable.jennie1,R.drawable.rose1,R.drawable.jisoo1};
private int pictureIndex = 0;
private int maxIndex = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonnext = (Button)findViewById(R.id.buttonnext);
buttonup = (Button)findViewById(R.id.buttonup);
imageView = (ImageView)findViewById(R.id.imageView);
buttonup.setOnClickListener(this::onClick);
buttonnext.setOnClickListener(this::onClick);
imageView.setImageResource(picture[3]);
}
public void onClick(View view)
{
switch (view.getId())
{
case R.id.buttonnext:
if (pictureIndex == maxIndex)
{
pictureIndex = 0;
}
else
{
pictureIndex = pictureIndex+1;
}
break;
case R.id.buttonup:
if (pictureIndex == 0)
{
pictureIndex = maxIndex;
}
else
{
pictureIndex = pictureIndex-1;
}
break;
default:
break;
}
imageView.setImageResource(picture[pictureIndex]);
}
}