📅  最后修改于: 2020-09-30 00:39:21             🧑  作者: Mango
Android图像滑块将整个屏幕滑到另一屏幕。图像滑块由支持库提供的ViewPager创建。要实现图像滑块,您需要继承扩展PagerAdapter的ViewPager类。
让我们来看一个Android图片滑块的示例。
在activity_main.xml文件中,我们将ViewPager包装在RelativeLayout中。
文件:activity_main.xml
文件:MainActivity.java
package com.example.test.imageslider;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager mViewPager = (ViewPager) findViewById(R.id.viewPage);
ImageAdapter adapterView = new ImageAdapter(this);
mViewPager.setAdapter(adapterView);
}
}
现在创建ImageAdapter类,该类扩展了用于Android图像滑块的PagerAdapter。
将一些图像放在要滑动的可绘制文件夹中。
文件:ImageAdapter.java
package com.example.test.imageslider;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter{
Context mContext;
ImageAdapter(Context context) {
this.mContext = context;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
private int[] sliderImageId = new int[]{
R.drawable.image1, R.drawable.image2, R.drawable.image3,R.drawable.image4, R.drawable.image5,
};
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(sliderImageId[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
@Override
public int getCount() {
return sliderImageId.length;
}
}
我们需要重写PagerAdapter类的以下方法。
输出量