android+studio图片切换
时间: 2023-12-05 18:41:12 浏览: 109
Android studio ViewPager2图片切换+底部圆点指示器应用设计
5星 · 资源好评率100%
以下是在Android Studio中实现图片切换的步骤:
1. 在res/layout文件夹下创建一个新的XML布局文件,例如image_switcher.xml,用于显示ImageSwitcher控件。
2. 在image_switcher.xml文件中添加以下代码:
```xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageSwitcher
android:id="@+id/image_switcher"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
```
3. 在MainActivity.java文件中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private ImageSwitcher imageSwitcher;
private int[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3};
private int currentIndex = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_switcher);
imageSwitcher = findViewById(R.id.image_switcher);
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
ImageView imageView = new ImageView(getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
return imageView;
}
});
imageSwitcher.setImageResource(images[currentIndex]);
imageSwitcher.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentIndex++;
if (currentIndex == images.length) {
currentIndex = 0;
}
imageSwitcher.setImageResource(images[currentIndex]);
}
});
}
}
```
4. 运行应用程序,单击ImageSwitcher控件即可切换图片。
阅读全文