android studio图片轮播布局代码
时间: 2023-12-21 09:03:18 浏览: 113
图片轮播代码
5星 · 资源好评率100%
以下是一个Android Studio图片轮播布局的代码示例:
```java
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
public class ImageSlider extends FrameLayout {
private Context mContext;
private ViewPager mViewPager;
private LinearLayout mIndicatorLayout;
private List<ImageView> mIndicatorViews;
private List<Integer> mImageList;
private int mCurrentPosition = 0;
private Handler mHandler;
private Runnable mRunnable;
public ImageSlider(Context context) {
this(context, null);
}
public ImageSlider(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ImageSlider(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
LayoutInflater.from(context).inflate(R.layout.image_slider_layout, this);
mViewPager = findViewById(R.id.viewPager);
mIndicatorLayout = findViewById(R.id.indicatorLayout);
mImageList = new ArrayList<>();
mIndicatorViews = new ArrayList<>();
mHandler = new Handler();
mRunnable = new Runnable() {
@Override
public void run() {
mCurrentPosition++;
if (mCurrentPosition >= mImageList.size()) {
mCurrentPosition = 0;
}
mViewPager.setCurrentItem(mCurrentPosition);
mHandler.postDelayed(this, 3000);
}
};
}
public void setImageList(List<Integer> imageList) {
mImageList.clear();
mImageList.addAll(imageList);
initViewPager();
initIndicator();
startAutoPlay();
}
private void initViewPager() {
ImageSliderAdapter adapter = new ImageSliderAdapter(mContext, mImageList);
mViewPager.setAdapter(adapter);
mViewPager.setCurrentItem(mCurrentPosition);
}
private void initIndicator() {
mIndicatorLayout.removeAllViews();
mIndicatorViews.clear();
for (int i = 0; i < mImageList.size(); i++) {
ImageView indicatorView = new ImageView(mContext);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(10, 0, 10, 0);
indicatorView.setLayoutParams(params);
if (i == mCurrentPosition) {
indicatorView.setImageResource(R.drawable.indicator_selected);
} else {
indicatorView.setImageResource(R.drawable.indicator_unselected);
}
mIndicatorViews.add(indicatorView);
mIndicatorLayout.addView(indicatorView);
}
}
private void startAutoPlay() {
mHandler.postDelayed(mRunnable, 3000);
}
private void stopAutoPlay() {
mHandler.removeCallbacks(mRunnable);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
stopAutoPlay();
}
}
```
请注意,上述代码是一个自定义的图片轮播布局,需要在布局文件中引用。同时,还需要创建一个适配器类`ImageSliderAdapter`来设置ViewPager的内容。
阅读全文