在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中左右滑動。