android的ViewPager实现加载网络图片并自动轮播

弄个图好看点。

gif

阅读本文之前, 先看下前面打底的两篇文章。

前面已经实现了循环效果和自动播放, 现在我们来实现加载网络图片。

使用的是第三方库 facebook的Fresco

原文

android的ViewPager实现加载网络图片并自动轮播

代码

同以前一样, 注意点用注释的形式给出。

这次需要注意下的地方有

  • build.gradle中加入Fresco
  • AndroidManifest.xml中加入访问网络的权限
  • App.java中初始化Fresco

AndroidManifest.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.qefee.pj.testviewpager">


<!--网络权限-->
<uses-permission android:name="android.permission.INTERNET"/>

<application
android:name=".App"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

App.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.qefee.pj.testviewpager;

import android.app.Application;

import com.facebook.drawee.backends.pipeline.Fresco;

public class App extends Application {
@Override
public void onCreate() {
super.onCreate();

Fresco.initialize(this); // 初始化Fresco
}
}

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package com.qefee.pj.testviewpager;

import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.drawee.view.SimpleDraweeView;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
/**
* log tag for MainActivity
*/

private static final String TAG = "MainActivity";

ViewPager viewPager;

String[] imageUris = {
"https://pic4.zhimg.com/03b2d57be62b30f158f48f388c8f3f33_b.png",
"https://pic1.zhimg.com/4373a4f045e5e9ae16ebd6a624bf6228_b.png",
"https://pic2.zhimg.com/0364e17a1561f48793993d8bf1cdc785_b.png",
"https://pic2.zhimg.com/55fa74ff3eba164ed1db2037df1a8311_b.png",
"https://pic4.zhimg.com/5dc30569c06e7c6266c9809f6eb80a7b_b.jpg"
};

SimpleDraweeView[] simpleDraweeViews;

int currentItem;
private ScheduledExecutorService executor;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

int size = initSize();
initTextViews(size);
initViewPager();
}

@Override
protected void onResume() {
super.onResume();

startAutoScroll(); // activity激活时候自动播放
}

@Override
protected void onPause() {
super.onPause();

stopAutoScroll(); // activity暂停时候停止自动播放
}

private void startAutoScroll() {
stopAutoScroll();

executor = Executors.newSingleThreadScheduledExecutor();
Runnable command = new Runnable() {
@Override
public void run() {
selectNextItem();
}

private void selectNextItem() {
runOnUiThread(new Runnable() {
@Override
public void run() {
viewPager.setCurrentItem(++currentItem);
}
});
}
};
int delay = 2;
int period = 2;
TimeUnit timeUnit = TimeUnit.SECONDS;
executor.scheduleAtFixedRate(command, delay, period, timeUnit);
}

private void stopAutoScroll() {
if (executor != null) {
executor.shutdownNow();
}
}

private void initViewPager() {
viewPager = (ViewPager) findViewById(R.id.viewPage);

viewPager.setAdapter(new PagerAdapter() {
@Override
public int getCount() {
return Integer.MAX_VALUE; // 取一个大数字
}

@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
Log.i(TAG, "instantiateItem: instantiateItem + position = " + position);
SimpleDraweeView t = simpleDraweeViews[position % simpleDraweeViews.length];
container.addView(t);

Uri uri = Uri.parse(imageUris[position % simpleDraweeViews.length]);
t.setImageURI(uri);

return t;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
Log.i(TAG, "destroyItem: + position = " + position);
container.removeView((View) object);
}
});

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

@Override
public void onPageSelected(int position) {
currentItem = position;

startAutoScroll(); // 手动切换完成后恢复自动播放
}

@Override
public void onPageScrollStateChanged(int state) {

}
});

currentItem = imageUris.length * 1000000; // 取一个中间的大数字, 防止接近边界
viewPager.setCurrentItem(currentItem);
}

private void initTextViews(int size) {
SimpleDraweeView[] tvs = new SimpleDraweeView[size];

for (int i = 0; i < tvs.length; i++) {
tvs[i] = new SimpleDraweeView(this);
tvs[i].getHierarchy().setPlaceholderImage(R.mipmap.ic_launcher);

ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
tvs[i].setLayoutParams(layoutParams);
simpleDraweeViews = tvs;
}
}

private int initSize() {
int size;
if (imageUris.length > 3) {
size = imageUris.length;
} else {
size = imageUris.length * 2; // 小于3个时候, 需要扩大一倍, 防止出错
}
return size;
}
}

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.qefee.pj.testviewpager.MainActivity">


<android.support.v4.view.ViewPager
android:id="@+id/viewPage"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</RelativeLayout>

build.gradle (app)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.3"

defaultConfig {
applicationId "com.qefee.pj.testviewpager"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'

// 加入Fresco
compile 'com.facebook.fresco:fresco:0.10.0'
}
Fork me on GitHub