>웹 프론트엔드 >HTML 튜토리얼 >ViewPager+Fragment+广播来实现一个滑动页面切换_html/css_WEB-ITnose

ViewPager+Fragment+广播来实现一个滑动页面切换_html/css_WEB-ITnose

WBOY
WBOY원래의
2016-06-24 11:49:551178검색




要实现这样一个页面,上面的好说,下面的是一个滑动视图,我们想到的是用viewpager来实现,但是这个有一个问题,按照平时的写法,我们会写5个Activity放到viewpager里面去,这自然是可以实现的。但是这里有一个问题,一进来,在主界面manager.startActivity(id, intent).getDecorView();来取得view加到viewpager里,这样一启动,五个子界面都同时启动,都去加载数据,会导致很卡,也浪费了资源,我们想法是,默认只加载第一个页面,滑到第二个才开始加载第二个的数据,但是通过监听事件发现,一开始启动,五个Activity的oncreate方法都运行了。再滑动切换,是没有任何监听或者实现方法得到调用的。


这里后来想到了另外一个方法:我们用viewpager+5个Fragment+广播机制去通知他更新。

在主界面我们可以这样写。

/**	 * 初始化PageViewer	 */	List<fragment> list;	FragmentPagerAdapter myPagerAdapter;	FragmentManager SupportfragmentManager = getSupportFragmentManager();	private void initPagerViewer(){		Label1AllOrder lable1 = new Label1AllOrder();		Label2WinPrizeOrder lable2 = new Label2WinPrizeOrder();		Label3WaitForLotteryOrder lable3 = new Label3WaitForLotteryOrder();		Label4ZhuiHaoOrder lable4 = new Label4ZhuiHaoOrder();		Label5BuyTogetherOrder lable5 = new Label5BuyTogetherOrder();				list = new ArrayList<fragment>();  		list.add(lable1);		list.add(lable2);		list.add(lable3);		list.add(lable4);		list.add(lable5);				myPagerAdapter = new MyPagerAdapter(SupportfragmentManager);        view_pager.setAdapter(myPagerAdapter);         view_pager.setOnPageChangeListener(new MyOnPageChangeListener()); 	}	/**	 * Pager适配器	 */	public class MyPagerAdapter extends FragmentPagerAdapter {		public MyPagerAdapter(FragmentManager fm) {			super(fm);		}		@Override		public Fragment getItem(int arg0) {			return list.get(arg0);  		}		@Override		public int getCount() {			return list.size();		}				/*@Override		public Object instantiateItem(View arg0, int arg1) {			//ViewPager pViewPager = ((ViewPager) arg0);			//pViewPager.addView(list.get(arg1).getView());			return list.get(arg1);		}				@Override		public void destroyItem(ViewGroup container, int position, Object object) {			//ViewPager pViewPager = ((ViewPager) container);			//pViewPager.removeView(list.get(position).getView());		}*/	}		private void sendBroadcastDoRefreshByCurrentIndex(){		switch (currentIndex) {		case 0:			sendBroadcastDoRefresh("action.Label1AllOrder");			break;		case 1:			sendBroadcastDoRefresh("action.Label2WinPrizeOrder");			break;		case 2:			sendBroadcastDoRefresh("action.Label3WaitForLotteryOrder");			break;		case 3:			sendBroadcastDoRefresh("action.Label4ZhuiHaoOrder");			break;		case 4:			sendBroadcastDoRefresh("action.Label5BuyTogetherOrder");			break;		default:			break;		}	}		Intent broadCastIntent = new Intent();	// 广播通知	private void sendBroadcastDoRefresh(String action){		broadCastIntent.setAction(action);        sendBroadcast(broadCastIntent);	}		/**	 * 页卡切换监听	 */		private int currentIndex = 0;	public class MyOnPageChangeListener implements OnPageChangeListener {		@Override		public void onPageSelected(int index) {			currentIndex = index;			System.out.println("-onPageSelected--------" + index);			initViewPagePoint(index);			switch (index) {			case 0:				sendBroadcastDoRefresh("action.Label1AllOrder");				view_pager_tip.setText("全部订单");				break;			case 1:				sendBroadcastDoRefresh("action.Label2WinPrizeOrder");				view_pager_tip.setText("中奖订单");				break;			case 2:				sendBroadcastDoRefresh("action.Label3WaitForLotteryOrder");				view_pager_tip.setText("待开奖订单");				break;			case 3:				sendBroadcastDoRefresh("action.Label4ZhuiHaoOrder");				view_pager_tip.setText("追号订单");				break;			case 4:				sendBroadcastDoRefresh("action.Label5BuyTogetherOrder");				view_pager_tip.setText("合买订单");				break;			default:				break;			}		}		@Override		public void onPageScrollStateChanged(int arg0) {			 		}		@Override		public void onPageScrolled(int arg0, float arg1, int arg2) {		}	}</fragment></fragment>

每滑动一下,就发送广播,通知子界面去更新。但是是不是每次更新就有他自己控制了

在五个子Fragment我们可以这样写:其实这里五个是相似了。我就贴一个的代码

public class Label2WinPrizeOrder extends Fragment implements OnClickListener {	Activity activity = Label2WinPrizeOrder.this.getActivity();		 	@Override	public void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);				LayoutInflater inflater = getActivity().getLayoutInflater();		mainView = inflater.inflate(R.layout.my_lottery_user_center_label2_win_prize, (ViewGroup)getActivity().findViewById(R.id.my_lottery_user_center_viewpage), false);		initUI();		 				initNoDataUI();				//注册刷新广播		IntentFilter intentFilter = new IntentFilter();		intentFilter.addAction("action.Label2WinPrizeOrder");		getActivity().registerReceiver(mRefreshBroadcastReceiver, intentFilter);						 	}		@Override      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)  { 		ViewGroup p = (ViewGroup) mainView.getParent();		if(p!=null){			p.removeAllViewsInLayout();		}				return mainView;     }			@Override	public void onActivityCreated(Bundle savedInstanceState) {		super.onActivityCreated(savedInstanceState);	}		 		// broadcast receiver	private BroadcastReceiver mRefreshBroadcastReceiver = new BroadcastReceiver() {		@Override		public void onReceive(Context context, Intent intent) {			String action = intent.getAction();			if (action.equals("action.Label2WinPrizeOrder")) {				System.out.println("---------------action.Label2WinPrizeOrder"); 							if (AutoUpdate.isNetworkAvailable(activity)) {					if(canLoadAgain){						loadingRelativelayout.setVisibility(View.VISIBLE);						noDataLinearlayout.setVisibility(View.GONE);						hasDataLinearlayout.setVisibility(View.GONE);												updateInitLotteryInfo();												page = 0;						mListView.mEndRootView.setVisibility(View.GONE);						mListView.setAutoLoadMore(true);						mListView.setCanRefresh(true);						new getDataTask().execute(1);					}				}								setK3ballVisible();			}		}	};	//初设化彩种信息	private void updateInitLotteryInfo(){		if(MyLotterActivity.labelsListData != null && MyLotterActivity.labelsListData.size() >= 2){			MyLotteryLabelBean bean = MyLotterActivity.labelsListData.get(1);			if(FunctionUtil.strNotNull(bean.getLottery_type_index())){				if("308".equals(bean.getLottery_type_index())){					lottery_type_index = 308;				}else if("309".equals(bean.getLottery_type_index())){					lottery_type_index = 309;				}else if("310".equals(bean.getLottery_type_index())){					lottery_type_index = 310;				}			}						if(FunctionUtil.strNotNull(bean.getTitle())){				title = bean.getTitle();			}						tipTextview.setText(title);		}	}		private void initUI() {		activity = getActivity();		loadingRelativelayout = (LinearLayout) mainView.findViewById(R.id.my_lottery_user_center_label2_loading_rel);		loadAgainRelativelayout = (RelativeLayout) mainView.findViewById(R.id.my_lottery_user_center_label2_load_again_rel);		hasDataLinearlayout = (LinearLayout) mainView.findViewById(R.id.my_lottery_user_center_label2_has_data_linear);		noDataLinearlayout = (LinearLayout) mainView.findViewById(R.id.my_lottery_user_center_label2_no_data_linear);
<span style="white-space:pre">	</span>}
 

这样。我们每次滑动一次就能在五个子类,得到一次广播通知。就让他去加载数据,当第二次在滑动到那个,他依然可以收到广播,至于要不要再去刷新数据,就看你怎么控制了。









성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.