Home Web Front-end HTML Tutorial ViewPager Fragment broadcast to implement a sliding page switching_html/css_WEB-ITnose

ViewPager Fragment broadcast to implement a sliding page switching_html/css_WEB-ITnose

Jun 24, 2016 am 11:49 AM




To implement such a page, the above is easy to say, and the following is a sliding view, What we think of is to use viewpager to implement it, but there is a problem with this. According to the usual writing method, we will write 5 activities and put them in viewpager, which can naturally be achieved. But there is a problem here. Once you come in, go to the main interface manager.startActivity(id, intent).getDecorView(); to get the view and add it to the viewpager. Once started, the five sub-interfaces will start at the same time and load data. It causes a lot of lag and wastes resources. Our idea is to only load the first page by default, and only start loading the data of the second page after sliding to the second page. However, through monitoring events, we found that at the beginning, the oncreate of five activities All methods are run. When sliding to switch again, no monitoring or implementation methods are called.


I later thought of another method: we use the viewpager 5 Fragment broadcast mechanism to notify him of updates.

In the main interface we can write like this.

/**	 * 初始化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) {		}	}
Copy after login

Every time you slide, a broadcast is sent to notify the sub-interface to update. But does it have its own control every time it is updated?

In the five sub-Fragments, we can write like this: In fact, the five here are similar. I will post a code

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);
Copy after login
<span style="white-space:pre">	</span>}
Copy after login

like this. Every time we swipe, we can get a broadcast notification in five subcategories. Just let him load the data. When he slides to that point for the second time, he can still receive the broadcast. As for whether to refresh the data again, it depends on how you control it.









Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the viewport meta tag? Why is it important for responsive design? What is the viewport meta tag? Why is it important for responsive design? Mar 20, 2025 pm 05:56 PM

The article discusses the viewport meta tag, essential for responsive web design on mobile devices. It explains how proper use ensures optimal content scaling and user interaction, while misuse can lead to design and accessibility issues.

What is the purpose of the <iframe> tag? What are the security considerations when using it? What is the purpose of the <iframe> tag? What are the security considerations when using it? Mar 20, 2025 pm 06:05 PM

The article discusses the &lt;iframe&gt; tag's purpose in embedding external content into webpages, its common uses, security risks, and alternatives like object tags and APIs.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

See all articles