在Android中,要实现图片滑动,可以使用ViewPager和RecyclerView。这里我们使用ViewPager来实现图片滑动。
build.gradle
文件中添加依赖:dependencies {
implementation 'com.android.support:support-v4:28.0.0'
}
res/layout
目录下创建一个新的布局文件activity_image_slider.xml
,并添加ViewPager:<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ImageSliderActivity
,并在其中设置ViewPager的适配器:import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
public class ImageSliderActivity extends AppCompatActivity {
private ViewPager viewPager;
private int[] imageResources = {R.drawable.image1, R.drawable.image2, R.drawable.image3};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_slider);
viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(new ImageSlideAdapter(this, imageResources));
}
}
ImageSlideAdapter
,继承自PagerAdapter
,并实现其方法:import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
public class ImageSlideAdapter extends PagerAdapter {
private Context context;
private int[] imageResources;
private LayoutInflater inflater;
public ImageSlideAdapter(Context context, int[] imageResources) {
this.context = context;
this.imageResources = imageResources;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return imageResources.length;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
View imageLayout = inflater.inflate(R.layout.image_slide, container, false);
ImageView imageView = imageLayout.findViewById(R.id.image);
imageView.setImageResource(imageResources[position]);
container.addView(imageLayout);
return imageLayout;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
}
res/layout
目录下创建一个新的布局文件image_slide.xml
,并添加ImageView:<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
</LinearLayout>
AndroidManifest.xml
中添加ImageSliderActivity
:
现在,你已经成功实现了图片滑动功能。运行应用程序,你将看到图片可以在ViewPager中左右滑动。