动态加载ViewPager(服务器有几张显示几页+定时)

package com.bjypt.vipcard.activity;




import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;


import com.bjypt.vipcard.BaseActivity;
import com.bjypt.vipcard.R;
import com.bjypt.vipcard.net.HttpRequest;
import com.bjypt.vipcard.net.Log;
import com.bjypt.vipcard.net.mAjaxCallBack;
import com.bjypt.vipcard.utils.ImageUtils;
import com.bjypt.vipcard.utils.ToastUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;




public class WelcomeActivity extends BaseActivity implements OnClickListener{
	private ViewPager viewPager; // android-support-v4中的滑动组件
	private List<ImageView> imageViews; // 滑动的图片集合
	private List<View> dots; // 图片标题正文的那些点
	private int currentItem = 0; // 当前图片的索引号
	private ImageView dot;//  圆圈图标
	private LinearLayout ll;//动态添加圆圈的LinearLayout
	private ArrayList<String>imageUrl;//图片地址集合
	private ImageLoader imageLoader;
	private DisplayImageOptions options;
	private TextView tv_toMain;//顶部的跳过按钮
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_welcome);
		tv_toMain = (TextView) findViewById(R.id.tv_toMain);
		tv_toMain.setOnClickListener(this);
		ll = (LinearLayout) findViewById(R.id.ll);
		imageUrl =new ArrayList<String>();
		imageViews = new ArrayList<ImageView>();
		dots = new ArrayList<View>();
		imageLoader = ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
		.cacheInMemory(true)
		.cacheOnDisc(true)
		.showStubImage(R.drawable.welcome)
		// 设置图片下载期间显示的图片
		.showImageForEmptyUri(R.drawable.welcome)
		// 设置图片uri为空时显示的图片
		.showImageOnFail(R.drawable.welcome)
		// 设置图片加载或解码转换失败时显示的图片
		.considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.imageScaleType(ImageScaleType.EXACTLY).build();


		if (!imageLoader.isInited()) {
			ImageUtils.initImageLoader(this);
		}
		viewPager = (ViewPager) findViewById(R.id.vp);
	}


	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		get();


	}


	private void getFail(){
		imageUrl.add("");
		ImageView imageView = new ImageView(this);
		imageView.setScaleType(ScaleType.CENTER_CROP);
		imageView.setImageResource(R.drawable.welcome);
		//imageView.setBackgroundResource(R.drawable.welcome);
		imageViews.add(imageView);
		viewPager.setAdapter(new MyAdapter());// 设置填充ViewPager页面的适配器
		// 设置一个监听器,当ViewPager中的页面改变时调用
		viewPager.setOnPageChangeListener(new MyPageChangeListener());
		// 当Activity显示出来后,每两秒钟切换一次图片显示
		handler.postDelayed(run, 3000);




	}
	private void getImageUrl(){
		// 初始化图片资源
		for (int i = 0; i < imageUrl.size(); i++) {
			ImageView imageView = new ImageView(this);
			//imageView.setImageResource(imageResId[i]);
			imageView.setScaleType(ScaleType.CENTER_CROP);
			imageLoader.displayImage(HttpRequest.ImgURL+imageUrl.get(i), imageView,
					options);
			imageViews.add(imageView);
			dot = new ImageView(this,null,R.style.dot_style);
			dot.setScaleType(ScaleType.FIT_XY);
			LayoutParams lp = new LayoutParams(15,15);


			if(i == 0)
				dot.setBackgroundResource(R.drawable.dot_focused);
			else
				dot.setBackgroundResource(R.drawable.dot_normal);
			lp.leftMargin = 3;
			lp.rightMargin = 3;


			dots.add(dot);
			ll.addView(dot, lp);
		}
		viewPager.setAdapter(new MyAdapter());// 设置填充ViewPager页面的适配器
		// 设置一个监听器,当ViewPager中的页面改变时调用
		viewPager.setOnPageChangeListener(new MyPageChangeListener());
		// 当Activity显示出来后,每3秒钟切换一次图片显示
		handler.postDelayed(run, 3000);
	}


	/**
	 * 当ViewPager中页面的状态发生改变时调用
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyPageChangeListener implements OnPageChangeListener {
		private int oldPosition = 0;


		/**
		 * This method will be invoked when a new page becomes selected.
		 * position: Position index of the new selected page.
		 */
		public void onPageSelected(int position) {
			currentItem = position;
			//tv_title.setText(titles[position]);
			dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
			dots.get(position).setBackgroundResource(R.drawable.dot_focused);
			oldPosition = position;
		}


		public void onPageScrollStateChanged(int arg0) {


		}


		public void onPageScrolled(int arg0, float arg1, int arg2) {


		}
	}


	/**
	 * 填充ViewPager页面的适配器
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyAdapter extends PagerAdapter {


		@Override
		public int getCount() {
			return imageUrl.size();
		}


		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}


		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}


		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {


		}


		@Override
		public Parcelable saveState() {
			return null;
		}


		@Override
		public void startUpdate(View arg0) {


		}


		@Override
		public void finishUpdate(View arg0) {


		}
		@Override
		public Object instantiateItem(View container, int position) {
			View view = imageViews.get(position);
			ViewPager viewPager = (ViewPager) container;
			viewPager.addView(view);
			return imageViews.get(position);


		}
	}


	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch(arg0.getId()){
		case R.id.tv_toMain:
			handler.removeCallbacks(run);
			//Toast.makeText(WelcomeActivity.this, "按钮", Toast.LENGTH_SHORT).show();
			startActivity(new Intent(this, MainActivity.class));
			finish();
			break;
		}


	}


	private void get() {
		/**
		 * 请求网络
		 */
		HashMap<String, Object> map = new HashMap<String, Object>();


		map = HttpRequest.GetsysAdList();


		HttpPost(map, true,new mAjaxCallBack<Object>() {
			@Override
			public void onLoading(long count, long current) {
				super.onLoading(count, current);
			}
			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				Log.e("成功", t.toString());
				try {
					JSONObject obj = new JSONObject(t.toString());
					if("0".equals(obj.get("resultStatus"))){
						JSONArray jsonArray = obj.getJSONArray("result");
						for(int i = 0;i<jsonArray.length();i++){
							JSONObject  json = jsonArray.getJSONObject(i);
							imageUrl.add(json.getString("adurl"));
						}
						if(imageUrl.size()>0){


							getImageUrl();
						}else{
							getFail();
						}
					}else{
						Hint(obj.getString("msg")+"");
						getFail();
					}


				} catch (JSONException e) {
					Hint(e.toString());
					getFail();
				}
			}
			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				super.onFailure(t, errorNo, strMsg);
				Hint(t.toString());
				getFail();


			}
		});
	}
	private void Hint(String message){


		ToastUtils.toast(this, message);
	}
	// 切换当前显示的图片
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if(currentItem < imageViews.size()-1){


				currentItem = currentItem+1;
				viewPager.setCurrentItem(currentItem);// 切换当前显示的图片
				handler.postDelayed(run, 3000);
			}else{
				handler.removeCallbacks(run);
				WelcomeActivity.this.startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
				WelcomeActivity.this.finish();
			}


		};
	};
	public Runnable run = new Runnable() {


		@Override
		public void run() {
			// TODO Auto-generated method stub
			handler.obtainMessage().sendToTarget(); // 通过Handler切换图片


		}
	};




}
xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rr"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >
   


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


    <TextView
        android:id="@+id/tv_toMain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:text="跳过"
        android:textColor="#000000"
        android:textSize="18sp" />


    <LinearLayout
        android:id="@+id/ll"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:gravity="center"
        android:orientation="horizontal" />


</RelativeLayout>

<pre name="code" class="java">dot_style.xml
<style name="dot_style">
        <item name="android:layout_width">5dp</item>
        <item name="android:layout_height">5dp</item>
        <item name="android:background">@drawable/dot_normal</item>
        <item name="android:layout_marginLeft">3dp</item>
        <item name="android:layout_marginRight">3dp</item>
    </style>

R.drawable.dot_focused

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >
 
     <!-- 获取焦点的shape图形 -->
    <corners android:radius="5dip" />
    <solid android:color="#aaFFFFFF" />
</shape>
<pre name="code" class="java">R.drawable.dot_normal

 
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
       android:shape="oval">
    <!-- 正常的shape图形 -->
     <corners android:radius="5dip" />
     <solid android:color="#55000000" />
</shape>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值