MainActivity
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what == 0){
//viewPager显示下一页
viewPager.setCurrentItem(viewPager.getCurrentItem() +1);
//再次发送延时消息
handler.sendEmptyMessageDelayed(0,2000);
}
}
};
private LinearLayout linearLayout;
private List<ImageView> images;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.view_pager);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
//获取轮播图的数据
getDataFromNet();
}
private void getDataFromNet() {
AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
String path = "http://www.yulin520.com/a2a/impressApi/news/mergeList?pageSize=5&page=1";
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode == 200){
InputStream inputStream = connection.getInputStream();
String json = streamToString(inputStream,"utf-8");
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
//打印以下数据看看是否获取到
Log.i("----",s);
if (s != null){
Gson gson = new Gson();
DataDataBean dataDataBean = gson.fromJson(s, DataDataBean.class);
List<DataDataBean.DataBean> list = dataDataBean.getData();
//给viewPager设置适配器
MyAdapter myAdapter = new MyAdapter(MainActivity.this, list,handler);
//设置适配器
viewPager.setAdapter(myAdapter);
//3.根据集合的长度动态添加小圆点...linearLayout
initDoc(list);
//2.手动的可以无限滑动
viewPager.setCurrentItem(list.size()*100000);//设置当前展示中间某个足够大的位置
handler.sendEmptyMessageDelayed(0,2000);//发送一个延时的空消息
//viewPage设置监听事件
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
/**
* 当选中某个页面的时候,把当前的小圆点背景变成绿色
* @param position
*/
@Override
public void onPageSelected(int position) {
for (int i=0;i<images.size();i++){
if (i == position%images.size()){
images.get(i).setImageResource(R.drawable.shape_01);
}else {
images.get(i).setImageResource(R.drawable.shape_02);
}
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
};
asyncTask.execute();
}
/**
* 动态添加小圆点
* @param list
*/
private void initDoc(List<DataDataBean.DataBean> list) {
//1.需要一个集合记录一下小圆点的imageView控件
images = new ArrayList<ImageView>();
//2...linearLayout上面的视图清空一下再去添加
linearLayout.removeAllViews();
for (int i=0;i<list.size();i++){
ImageView imageView = new ImageView(MainActivity.this);
if (i==0){
imageView.setImageResource(R.drawable.shape_01);
}else {
imageView.setImageResource(R.drawable.shape_02);
}
//添加到集合去
images.add(imageView);
//添加到线性布局上
//这是布局参数,,刚开始小圆点之间没有距离,所以使用java代码指定宽度高度,并且指定小圆点之间的距离
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(5,0,5,0);
linearLayout.addView(imageView,params);
}
}
private String streamToString(InputStream inputStream,String charset) {
try {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String s = null;
StringBuilder builder = new StringBuilder();
while ((s = bufferedReader.readLine()) != null){
builder.append(s);
}
bufferedReader.close();
return builder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
适配器
public class MyAdapter extends PagerAdapter {
Context context;
List<DataDataBean.DataBean> list;
Handler handler;
public MyAdapter(Context context, List<DataDataBean.DataBean> list, Handler handler) {
this.context = context;
this.list = list;
this.handler = handler;
}
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
/**
* viewPager具有预加载,默认的前后加载一页,,,默认的容器里面最多三页
* @param container
* @param position
* @return
*/
@Override
public Object instantiateItem(ViewGroup container, int position) {
//1.把这个当前展示的视图添加到容器中...container
ImageView imageView = new ImageView(context);
//..........使图片平铺整个imageView控件
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//imageLoader加载图片到这个imageView控件上
ImageLoader.getInstance().displayImage(list.get(position %list.size()).getImg(),imageView,ImageLoaderUtil.getDefaultOption());
//给imageView设置触摸的监听事件
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int action = motionEvent.getAction();//获取手指的动作
switch (action){
case MotionEvent.ACTION_DOWN://按下的动作...应该取消发送消息的操作
handler.removeCallbacksAndMessages(null);
break;
case MotionEvent.ACTION_MOVE://移动的动作
handler.removeCallbacksAndMessages(null);
break;
case MotionEvent.ACTION_CANCEL://取消
//重新发送
handler.sendEmptyMessageDelayed(0,2000);
break;
case MotionEvent.ACTION_UP://抬起的动作
handler.sendEmptyMessageDelayed(0,2000);
break;
}
//返回true表示自己处理触摸事件
return true;
}
});
container.addView(imageView);//添加到容器
//2.把当前展示的视图返回
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
//销毁视图
container.removeView((View) object);
}
}