首先看下效果圖和整個項目的結構
很簡單的一個項目英岭,這也是我在簡書寫的第一個項目荆烈,雖然簡單,但是我覺得很漂亮
現(xiàn)在開始分析代碼
首先看下MainActivity的代碼
public class MainActivity extends AppCompatActivity {
private int pagerWidth;
private ViewPager mViewPager;
private LinearLayout mNumLayout;//小圓點的layout
private List<String> imgList; //圖片資源list
private RelativeLayout ll_main; //viewpager的父布局
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll_main = (RelativeLayout) findViewById(R.id.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewPager);
mNumLayout = (LinearLayout) findViewById(R.id.bottom_layout);
mViewPager.setOffscreenPageLimit(3);
initImg();
//設置viewpager的寬度為屏幕的3/1 看起來比較好看,設置每個item的邊距-10 34-43行
pagerWidth = (int) (getResources().getDisplayMetrics().widthPixels * 3.0f / 9.0f);
ViewGroup.LayoutParams lp = mViewPager.getLayoutParams();
if (lp == null) {
lp = new ViewGroup.LayoutParams(pagerWidth, ViewGroup.LayoutParams.MATCH_PARENT);
} else {
lp.width = pagerWidth;
}
mViewPager.setLayoutParams(lp);
mViewPager.setPageMargin(-10);
//將主布局的觸摸事件分發(fā)給viewpager病涨。這樣整個界面都可以響應viewpager的滑動事件啰扛,
// 如果不設置,滑動事件只有中間viewpager的寬度區(qū)域
ll_main.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return mViewPager.dispatchTouchEvent(motionEvent);
}
});
//設置切換時候的動畫效果
mViewPager.setPageTransformer(true, new GallyPageTransformer());
//這個就是設置adapter
mViewPager.setAdapter(new MyViewPagerAdapter(this, imgList));
//設置默認第二項馆揉,沒有為什么就是看起來漂亮(從0開始的业舍,所以是setcurrentitem(1))
mViewPager.setCurrentItem(1, true);
//設置下面的小點點默認第二項
mNumLayout.getChildAt(1).setBackgroundResource(R.drawable.msg_img_ellipse13x);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
//首先還原所有的小點點
for (int i = 0; i < mNumLayout.getChildCount(); i++) {
mNumLayout.getChildAt(i).setBackgroundResource(R.drawable.msg_img_ellipse33x);
}
//在根據(jù)position拿到當前的位置,設置小點點的選中圖片
Button currentBt = (Button) mNumLayout.getChildAt(position);
currentBt.setBackgroundResource(R.drawable.msg_img_ellipse13x);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
//初始化數(shù)據(jù)
public void initImg() {
imgList = new ArrayList<>();
imgList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490984457722&di=6d7d3e20e07fc833fc606089d01132e6&imgtype=0&src=http%3A%2F%2Fimgst.izhangheng.com%2F2016%2F08%2Fnight-beauty-girl-3.jpg");
imgList.add("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2946550071,381041431&fm=11&gp=0.jpg");
imgList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490984320392&di=8290126f83c2a2c0d45be41e3f88a6d0&imgtype=0&src=http%3A%2F%2Ffile.mumayi.com%2Fforum%2F201307%2F19%2F152440r9ov9ololkzdcz7d.jpg");
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.msg_img_ellipse33x);
//根據(jù)圖片list的大小升酣,創(chuàng)建下面的小圓點按鈕
for (int i = 0; i < imgList.size(); i++) {
Button bt = new Button(this);
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(bitmap.getWidth(), bitmap.getHeight());
params1.setMargins(dip2px(5), 0, 0, 0);
bt.setLayoutParams(params1);
bt.setBackgroundResource(R.drawable.msg_img_ellipse33x);
mNumLayout.addView(bt);
}
}
//dip轉px的小工具方法
public int dip2px(float dpValue) {
final float scale = getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
首先實例化控件舷暮,
initImg();準備數(shù)據(jù)源
34-43行//設置viewpager的寬度為屏幕的3/1 看起來比較好看,設置每個item的邊距-10
46-51行//將主布局的觸摸事件分發(fā)給viewpager。這樣整個界面都可以響應viewpager的滑動事件噩茄,
// 如果不設置下面,滑動事件只有中間viewpager的寬度區(qū)域
接下來設置滑動事件,和適配器绩聘,我在代碼上面都有注釋沥割,應該能看得懂
接下來看下MyApplication
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Fresco.initialize(this);
}
}
viewpager的中間圖片我用的是SimpleDraweeView
所以在application中初始化了一下
接下來看下viewpager的適配器
public class MyViewPagerAdapter extends PagerAdapter {
private List<String> mlists;
private List<View> mSimpleDraweeViewList;
private HashMap<Integer, View> mViewIntegerHashMap = new HashMap<>();
private Context mContext;
public MyViewPagerAdapter(Context context, List<String> lists) {
mContext = context;
this.mlists = lists;
mSimpleDraweeViewList = new ArrayList<>();
}
@Override
public int getCount() {
return mlists.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view;
if (mViewIntegerHashMap.get(position) == null) {
view = View.inflate(mContext, R.layout.main_top_viewpager_item, null);
SimpleDraweeView simpleDraweeView = (SimpleDraweeView) view.findViewById(R.id.main_top_viewpager_item_simpl);
// FrescoUtils.loadImage(mContext,mlists.get(position),simpleDraweeView,10,10,10,10);
// simpleDraweeView.setImageResource(R.mipmap.ic_launcher);
simpleDraweeView.setImageURI(mlists.get(position));
container.addView(view);
mSimpleDraweeViewList.add(view);
mViewIntegerHashMap.put(position, view);
} else {
view = mViewIntegerHashMap.get(position);
}
return view;
/* SimpleDraweeView simpleDraweeView = new SimpleDraweeView(mContext);
simpleDraweeView.setImageURI(mlists.get(position));
container.addView(simpleDraweeView);
mSimpleDraweeViewList.add(simpleDraweeView);
return simpleDraweeView;*/
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(mViewIntegerHashMap.get(position));
}
}
item布局為
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/main_top_viewpager_item_simpl"
android:layout_width="150dp"
android:layout_height="180dp"
app:roundedCornerRadius="5dp"
app:roundingBorderColor="#ffffffff"
app:roundingBorderWidth="2dp"/>
</RelativeLayout>
item布局就是一個SimpleDraweeView
主要看下instantiateItem方法
首先判斷if(mViewIntegerHashMap.get(position) ==null) {
如果為空耗啦,就新建一個并且存起來,
下次直接拿出對應postiion的view返回
防止重復創(chuàng)建
最后看下GallyPageTransformer代碼
package cn.swt.m.btviewpager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
/**
* 介紹:這里寫介紹
* 作者:sweet
* 郵箱:sunwentao@priemdu.cn
* 時間: 2017/7/19
*/
public class GallyPageTransformer implements ViewPager.PageTransformer {
private static final float min_scale = 0.85f;
@Override
public void transformPage(View page, float position) {
//最小的縮放比例
float scaleFactor = Math.max(min_scale, 1 - Math.abs(position));
//旋轉的度數(shù)
float rotate = 40 * Math.abs(position);
Log.d("ss", "position" + position);
if (position < 0) {
//中間圖片左邊的圖片
page.setScaleX(scaleFactor);
page.setScaleY(scaleFactor);
page.setRotationY(rotate);
} else if (position >= 0 && position < 1) {
//中間圖片
page.setScaleX(scaleFactor);
page.setScaleY(scaleFactor);
page.setRotationY(-rotate);
} else if (position >= 1) {
//中間圖片右邊的圖片
page.setScaleX(scaleFactor);
page.setScaleY(scaleFactor);
page.setRotationY(-rotate);
}
}
}
主要是這個position會跟著滑動的距離進行改變机杜,所以想要動畫效果看起來很流暢帜讲,就得利用這個position函數(shù)
代碼不多 我都做了注釋
好像還差一個mainactivity的布局
貼在這里
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="200dp"
android:clipChildren="false"
android:layerType="software">
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="fitXY"
android:src="@drawable/tooopen_sy_169964521661"/>
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="150dp"
>
</android.support.v4.view.ViewPager>
<LinearLayout
android:paddingTop="5dp"
android:id="@+id/bottom_layout"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:orientation="horizontal">
</LinearLayout>
</RelativeLayout>
</RelativeLayout>