Android,BannerLayout 그래 픽 윤방 기능 구현
22531 단어 AndroidBannerLayout윤파
구현 효과 도:
(1)biuld.gradle 파일 에 추가
compile 'com.ydevelop:bannerlayout:1.0.4'
(2)BannerLayout 파일 만 들 기
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Interpolator;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class BannerLayout extends RelativeLayout {
private ViewPager mViewPager; //
// ( )
private LinearLayout indicatorContainer;
private Drawable unSelectedDrawable;
private Drawable selectedDrawable;
private int WHAT_AUTO_PLAY = 1000;
private boolean isAutoPlay = true; //
private int itemCount;
private int selectedIndicatorColor = 0xffff0000;
private int unSelectedIndicatorColor = 0x88888888;
private int titleBGColor = 0X33000000;
private int titleColor = 0Xffffffff;
private Shape indicatorShape = Shape.oval;
private int selectedIndicatorHeight = 20;
private int selectedIndecatorWidth = 20;
private int unSelectedIndicatorHeight = 20;
private int unSelectedIndecatorWidth = 20;
private int autoPlayDuration = 4000;
private int scrollDuration = 900;
//
private int indicatorSpace = 10;
//
private int indicatorMargin = 20;
private static final int titlePadding = 20;
private int defaultImage;
private enum Shape {
//
rect, oval
}
private OnBannerItemClickListener mOnBannerItemClickListener;
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if (msg.what == WHAT_AUTO_PLAY) {
if (mViewPager != null) {
mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
mHandler.sendEmptyMessageDelayed(WHAT_AUTO_PLAY, autoPlayDuration);
}
}
return false;
}
});
public BannerLayout(Context context) {
super(context);
init(null, 0);
}
public BannerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public BannerLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, defStyleAttr);
}
private void init(AttributeSet attrs, int defStyleAttr) {
TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.BannerLayoutStyle, defStyleAttr, 0);
selectedIndicatorColor = array.getColor(R.styleable.BannerLayoutStyle_selectedIndicatorColor, selectedIndicatorColor);
unSelectedIndicatorColor = array.getColor(R.styleable.BannerLayoutStyle_unSelectedIndicatorColor, unSelectedIndicatorColor);
titleBGColor = array.getColor(R.styleable.BannerLayoutStyle_titleBGColor, titleBGColor);
titleColor = array.getColor(R.styleable.BannerLayoutStyle_titleColor, titleColor);
int shape = array.getInt(R.styleable.BannerLayoutStyle_indicatorShape, Shape.oval.ordinal());
for (Shape shape1 : Shape.values()) {
if (shape1.ordinal() == shape) {
indicatorShape = shape1;
break;
}
}
selectedIndecatorWidth = (int) array.getDimension(R.styleable.BannerLayoutStyle_selectedIndicatorWidth, selectedIndecatorWidth);
selectedIndicatorHeight = (int) array.getDimension(R.styleable.BannerLayoutStyle_selectedIndicatorHeight, selectedIndicatorHeight);
unSelectedIndecatorWidth = (int) array.getDimension(R.styleable.BannerLayoutStyle_unSelectedIndicatorWidth, unSelectedIndecatorWidth);
unSelectedIndicatorHeight = (int) array.getDimension(R.styleable.BannerLayoutStyle_unSelectedIndicatorHeight, unSelectedIndicatorHeight);
indicatorSpace = (int) array.getDimension(R.styleable.BannerLayoutStyle_indicatorSpace, indicatorSpace);
indicatorMargin = (int) array.getDimension(R.styleable.BannerLayoutStyle_indicatorMargin, indicatorMargin);
autoPlayDuration = array.getInt(R.styleable.BannerLayoutStyle_autoPlayDuration, autoPlayDuration);
scrollDuration = array.getInt(R.styleable.BannerLayoutStyle_scrollDuration, scrollDuration);
isAutoPlay = array.getBoolean(R.styleable.BannerLayoutStyle_isAutoPlay, isAutoPlay);
defaultImage = array.getResourceId(R.styleable.BannerLayoutStyle_defaultImage, defaultImage);
array.recycle();
LayerDrawable unSelectedLayerDrawable;
LayerDrawable selectedLayerDrawable;
GradientDrawable unSelectedGradientDrawable = new GradientDrawable();
GradientDrawable selectedGradientDtawbale = new GradientDrawable();
switch (indicatorShape) {
case rect:
unSelectedGradientDrawable.setShape(GradientDrawable.RECTANGLE);
selectedGradientDtawbale.setShape(GradientDrawable.RECTANGLE);
break;
case oval:
unSelectedGradientDrawable.setShape(GradientDrawable.OVAL);
selectedGradientDtawbale.setShape(GradientDrawable.OVAL);
break;
}
unSelectedGradientDrawable.setColor(unSelectedIndicatorColor);
unSelectedGradientDrawable.setSize(unSelectedIndecatorWidth, unSelectedIndicatorHeight);
unSelectedLayerDrawable = new LayerDrawable(new Drawable[]{unSelectedGradientDrawable});
unSelectedDrawable = unSelectedLayerDrawable;
selectedGradientDtawbale.setColor(selectedIndicatorColor);
selectedGradientDtawbale.setSize(selectedIndecatorWidth, selectedIndicatorHeight);
selectedLayerDrawable = new LayerDrawable(new Drawable[]{selectedGradientDtawbale});
selectedDrawable = selectedLayerDrawable;
}
/**
*
*
* @param viewRes id
* @param titles ,
*/
public void setViewRes(List<Integer> viewRes, List<String> titles) {
List<View> views = new ArrayList<>();
itemCount = viewRes.size();
if (titles != null && titles.size() != viewRes.size()) {
throw new IllegalStateException("views.size() != titles.size()");
}
//
if (itemCount < 1) {
throw new IllegalStateException("item count not equal zero");
} else if (itemCount < 2) {
views.add(getFrameLayoutView(viewRes.get(0), titles != null ? titles.get(0) : null, 0));
views.add(getFrameLayoutView(viewRes.get(0), titles != null ? titles.get(0) : null, 0));
views.add(getFrameLayoutView(viewRes.get(0), titles != null ? titles.get(0) : null, 0));
} else if (itemCount < 3) {
views.add(getFrameLayoutView(viewRes.get(0), titles != null ? titles.get(0) : null, 0));
views.add(getFrameLayoutView(viewRes.get(1), titles != null ? titles.get(1) : null, 1));
views.add(getFrameLayoutView(viewRes.get(0), titles != null ? titles.get(0) : null, 0));
views.add(getFrameLayoutView(viewRes.get(1), titles != null ? titles.get(1) : null, 1));
} else {
for (int i = 0; i < viewRes.size(); i++) {
views.add(getFrameLayoutView(viewRes.get(i), titles != null ? titles.get(i) : null, i));
}
}
setViews(views);
}
//
public void setViewUrls(Context context,List<String> urls, List<String> titles) {
List<View> views = new ArrayList<>();
itemCount = urls.size();
Log.e("TAG",titles.size()+"---90---"+urls.size());
if (titles != null && titles.size() != itemCount) {
throw new IllegalStateException("views.size() != titles.size()");
}
// item 3 , 3
if (itemCount < 1) {// item 0
throw new IllegalStateException("item count not equal zero");
} else if (itemCount < 2) { // item 1
views.add(getFrameLayoutView(context,urls.get(0), titles != null ? titles.get(0) : null, 0));
views.add(getFrameLayoutView(context,urls.get(0), titles != null ? titles.get(0) : null, 0));
views.add(getFrameLayoutView(context,urls.get(0), titles != null ? titles.get(0) : null, 0));
} else if (itemCount < 3) {// item 2
views.add(getFrameLayoutView(context,urls.get(0), titles != null ? titles.get(0) : null, 0));
views.add(getFrameLayoutView(context,urls.get(1), titles != null ? titles.get(1) : null, 1));
views.add(getFrameLayoutView(context,urls.get(0), titles != null ? titles.get(0) : null, 0));
views.add(getFrameLayoutView(context,urls.get(1), titles != null ? titles.get(1) : null, 1));
} else {
for (int i = 0; i < urls.size(); i++) {
views.add(getFrameLayoutView(context,urls.get(i), titles != null ? titles.get(i) : null, i));
}
}
setViews(views);
}
private void setViews(final List<View> views) {
mViewPager = new ViewPager(getContext());
addView(mViewPager);
setSliderTransformDuration(scrollDuration);
// indicatorContainer
indicatorContainer = new LinearLayout(getContext());
indicatorContainer.setGravity(Gravity.CENTER_VERTICAL);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// ALIGN_PARENT_RIGHT CENTER_HORIZONTAL
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
// margin
params.setMargins(indicatorMargin, indicatorMargin, indicatorMargin, indicatorMargin);
// SliderLayout
addView(indicatorContainer, params);
// ,
for (int i = 0; i < itemCount; i++) {
ImageView indicator = new ImageView(getContext());
indicator.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
indicator.setPadding(indicatorSpace, indicatorSpace, indicatorSpace, indicatorSpace);
indicator.setImageDrawable(unSelectedDrawable);
indicatorContainer.addView(indicator);
}
LoopPagerAdapter pagerAdapter = new LoopPagerAdapter(views);
mViewPager.setAdapter(pagerAdapter);
// item Integer.MAX_VALUE , ok
// ,
int targetItemPosition = Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % itemCount;
mViewPager.setCurrentItem(targetItemPosition);
switchIndicator(targetItemPosition % itemCount);
mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
switchIndicator(position % itemCount);
}
});
startAutoPlay();
}
/**
*
*/
public void startAutoPlay() {
stopAutoPlay(); //
if (isAutoPlay) {
mHandler.sendEmptyMessageDelayed(WHAT_AUTO_PLAY, autoPlayDuration);
}
@Override
protected void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
if (visibility == VISIBLE) {
startAutoPlay();
} else {
stopAutoPlay();
}
}
/**
*
*/
public void stopAutoPlay() {
if (isAutoPlay) {
mHandler.removeMessages(WHAT_AUTO_PLAY);
}
}
private void setSliderTransformDuration(int scrollDuration) {
try {
Field mScroller = ViewPager.class.getDeclaredField("mScroller");
mScroller.setAccessible(true);
FixedSpeedScroller fixedSpeedScroller = new FixedSpeedScroller(mViewPager.getContext(), null, scrollDuration);
mScroller.set(mViewPager, fixedSpeedScroller);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
stopAutoPlay();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
startAutoPlay();
break;
}
return super.dispatchTouchEvent(ev);
}
/**
*
*
* @param currentPosition
*/
private void switchIndicator(int currentPosition) {
for (int i = 0; i < indicatorContainer.getChildCount(); i++) {
((ImageView) indicatorContainer.getChildAt(i)).setImageDrawable(i == currentPosition ? selectedDrawable : unSelectedDrawable);
}
}
public void setOnBannerItemClickListener(OnBannerItemClickListener onBannerItemClickListener) {
this.mOnBannerItemClickListener = onBannerItemClickListener;
}
@NonNull
private FrameLayout getFrameLayoutView(Context context, String url, String title, final int position) {
FrameLayout frameLayout = new FrameLayout(getContext());
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER;
ImageView imageView = new ImageView(getContext());
frameLayout.addView(imageView);
frameLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mOnBannerItemClickListener != null) {
mOnBannerItemClickListener.onItemClick(position);
}
}
});
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
if (defaultImage != 0){
Glide.with(getContext()).load(url).placeholder(defaultImage).centerCrop().into(imageView);
}else {
Glide.with(getContext()).load(url).centerCrop().into(imageView);
}
if (!TextUtils.isEmpty(title)) {
TextView textView = new TextView(getContext());
textView.setText(title);
textView.setTextColor(titleColor);
textView.setPadding(titlePadding, titlePadding, titlePadding, titlePadding);
textView.setBackgroundColor(titleBGColor);
textView.getPaint().setFakeBoldText(true);
layoutParams.gravity = Gravity.BOTTOM;
frameLayout.addView(textView, layoutParams);
}
return frameLayout;
}
@NonNull
private FrameLayout getFrameLayoutView(Integer res, String title, final int position) {
FrameLayout frameLayout = new FrameLayout(getContext());
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER;
ImageView imageView = new ImageView(getContext());
frameLayout.addView(imageView);
frameLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mOnBannerItemClickListener != null) {
mOnBannerItemClickListener.onItemClick(position);
}
}
});
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Glide.with(getContext()).load(res).centerCrop().into(imageView);
if (!TextUtils.isEmpty(title)) {
TextView textView = new TextView(getContext());
textView.setText(title);
textView.setTextColor(titleColor);
textView.setPadding(titlePadding, titlePadding, titlePadding, titlePadding);
textView.setBackgroundColor(titleBGColor);
textView.getPaint().setFakeBoldText(true);
layoutParams.gravity = Gravity.BOTTOM;
frameLayout.addView(textView, layoutParams);
}
return frameLayout;
}
public interface OnBannerItemClickListener {
void onItemClick(int position);
}
public class LoopPagerAdapter extends PagerAdapter {
private List<View> views;
public LoopPagerAdapter(List<View> views) {
this.views = views;
}
@Override
public int getCount() {
//Integer.MAX_VALUE = 2147483647
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
if (views.size() > 0) {
//position % view.size() position [0,view.size())
View view = views.get(position % views.size());
if (container.equals(view.getParent())) {
container.removeView(view);
}
container.addView(view);
return view;
}
return null;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
}
public class FixedSpeedScroller extends Scroller {
private int mDuration = 1000;
public FixedSpeedScroller(Context context) {
super(context);
}
public FixedSpeedScroller(Context context, Interpolator interpolator) {
super(context, (android.view.animation.Interpolator) interpolator);
}
public FixedSpeedScroller(Context context, Interpolator interpolator, int duration) {
this(context, interpolator);
mDuration = duration;
@Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
// Ignore received duration, use fixed one instead
super.startScroll(startX, startY, dx, dy, mDuration);
}
@Override
public void startScroll(int startX, int startY, int dx, int dy) {
// Ignore received duration, use fixed one instead
super.startScroll(startX, startY, dx, dy, mDuration);
}
}
}
(3)MainAvtivity.java 파일
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lenovo on 2018/4/23.
*/
public class MainActivity extends Activity {
private MyListView lv_zyb;
private ImageView iv_zybfh;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_zybfh=(ImageView) findViewById(R.id.iv_zybfh);
BannerLayout bannerLayout = (BannerLayout) findViewById(R.id.bannerzhuangyuanbang);
List<String> urls = new ArrayList<>();
urls.add("http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1404/02/c5/32731218_32731218_1396429876186.jpg");
urls.add("http://pic2.16pic.com/00/11/65/16pic_1165030_b.jpg");
urls.add("http://upload.17u.net/uploadpicbase/image/201708201147537103.jpg");
urls.add("http://img2.gzgov.gov.cn/gzsrmzf/dcgz/lyzx/rmjd/201709/W020170926622407643781.jpg");
urls.add("http://photocdn.sohu.com/20150324/Img410244363.jpg");
urls.add("http://pic4.40017.cn/scenery/destination/2017/01/10/11/SiTllI.jpg");
List<String> titleas = new ArrayList<>();
titleas.add(" ");
titleas.add(" ");
titleas.add(" ");
titleas.add(" ");
titleas.add(" ");
titleas.add(" ");
if (bannerLayout != null) {
bannerLayout.setViewUrls(this ,urls, titleas);
bannerLayout.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
@Override
public void onItemClick(int position) {
Toast.makeText(ZhuangyuanbangActivity.this, "position:" + position, Toast.LENGTH_SHORT).show();
}
});
}
}
}
(4)activity_main.xml 파일 입 니 다.빨간색 을 넣 어야 합 니 다.그렇지 않 으 면 app 시작 이 잘못 되 었 습 니 다.그리고 빨간색 은 가방 이름 입 니 다.자신의 프로젝트 로 바 꾼 가방 이름 을 기억 하 세 요.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<applwj.eduation.com.topeduation.BannerLayout
android:id="@+id/bannerzhuangyuanbang"
android:layout_width="match_parent"
android:layout_height="210dp"
app:scrollDuration="1000"
app:autoPlayDuration="3000"
app:unSelectedIndicatorHeight="10dp"
app:unSelectedIndicatorWidth="10dp"
app:selectedIndicatorHeight="10dp"
app:selectedIndicatorWidth="10dp"
app:unSelectedIndicatorColor="#99ffffff"
app:selectedIndicatorColor="#000000"
app:isAutoPlay="true"
/>
</LinearLayout>
demo 다운로드:안 드 로 이 드 는 그림 과 글 의 윤 방 기능 을 실현 한다.이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.