search
HomeWeb Front-endHTML TutorialViewPager_html/css_WEB-ITnose implemented by user guide sliding left and right

Continuing from the previous blog, the previous blog used ImageSwitcher to implement the user guide function, and now uses ViewPager to implement the same function. Look at the code directly:

Layout file activity_main.xml

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" tools:context=".MainActivity">       <android.support.v4.view.viewpager android:id="@+id/viewpager" android:layout_width="fill_parent" android:layout_height="fill_parent"></android.support.v4.view.viewpager>    <linearlayout android:id="@+id/dots" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:layout_marginbottom="50dp" android:gravity="center_horizontal" android:orientation="horizontal">    </linearlayout></relativelayout>

The switching of ViewPager pages uses small dots to indicate the current number. Page, here the drawable.xml file is used to draw, as follows:

dot_focus.xml

<?xml version="1.0" encoding="utf-8"?>  <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">      <corners android:radius="5dip"></corners>      <solid android:color="#FF930000"></solid></shape>
dot_nomal.xml

<?xml version="1.0" encoding="utf-8"?>  <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">      <corners android:radius="5dip"></corners>      <solid android:color="#FF3C3C3C"></solid></shape>
The following code in Activity:

package com.example.viewpagerautoswitch;import java.util.ArrayList;import java.util.List;import android.annotation.SuppressLint;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.support.v4.view.ViewPager;import android.support.v4.view.ViewPager.OnPageChangeListener;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup.LayoutParams;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;@SuppressLint("HandlerLeak")public class MainActivity extends Activity {	private ViewPager mViewPager ;	private MyPagerAdapter mViewPagerAdapter ;	private LinearLayout mLinearLayout ;	private ImageView[] mImageDots ;	private Context mContext ;		@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_main);		mContext = MainActivity.this ;		mViewPager = (ViewPager)findViewById(R.id.viewpager);		mLinearLayout = (LinearLayout)findViewById(R.id.dots);		initViewPager(getImageItem() ,0);	}		public void initViewPager(List<imageview> mList ,int position){		mImageDots = new ImageView[mList.size()];		for(int i=0 ;i<mlist.size imageview image="new" image.setlayoutparams layoutparams image.setbackgroundresource mimagedots mlinearlayout.addview textview tv="new" tv.setlayoutparams mviewpageradapter="new" mypageradapter mviewpager.setonpagechangelistener onpagechangelistener onpagescrollstatechanged> onPageSelected --> onPageScrolled -->onPageScrollStateChanged			@Override			public void onPageSelected(int position) {				for(int i=0 ;i<mimagedots.length if position mimagedots public void onpagescrolled current_position float persent int px onpagescrollstatechanged state mviewpager.setonclicklistener onclicklistener onclick view mviewpager.setadapter mviewpager.setcurrentitem list> getImageItem(){		List<imageview> list = new ArrayList<imageview>();		ImageView img = new ImageView(mContext);		img.setBackgroundResource(R.drawable.img1);		list.add(img);		img = new ImageView(mContext);		img.setBackgroundResource(R.drawable.img2);		list.add(img);		img = new ImageView(mContext);		img.setBackgroundResource(R.drawable.img3);		list.add(img);		return list ; 	}		@Override	public void finish() {		super.finish();	}}</imageview></imageview></mimagedots.length></mlist.size></imageview>
The difference between ViewPager and ImageSwitcher here is that ViewPager uses Adapter to encapsulate the pages that need to be installed, while ImageSwitcher uses ViewFactory to add them. Installing pictures. Therefore, when using viewPager, you need to integrate PagerAdapter to implement the corresponding interface. As follows:

MyPagerAdapter.java

package com.example.viewpagerautoswitch;import java.util.List;import android.content.Context;import android.support.v4.view.PagerAdapter;import android.support.v4.view.ViewPager;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;public class MyPagerAdapter extends PagerAdapter {		private List<imageview> items ; 	private Context mContext ;		public MyPagerAdapter(Context context,List<imageview> item){		mContext = context ;		items = item ;	}	@Override	public int getCount() {		return items == null ? 0 : items.size();	}	@Override	public boolean isViewFromObject(View view, Object obj) {		return view == (View)obj;	}		 @Override  	 public Object instantiateItem (ViewGroup container, int position) {  	        ImageView image = items.get(position); 	        ((ViewPager)container).addView(image, 0);  	        return image;  	 }  	      	 @Override  	 public void destroyItem (ViewGroup container, int position, Object object) {  	        container.removeView((View)object);  	 }  }</imageview></imageview>
In this way, the user guide function can be realized. The specific page effect is as follows: The picture shows the second pager In this case, this is a demo on an Android phone. If used on an Android set-top box, the left and right keys can be captured to slide the time.



Sometimes, in the application, it is not just to switch pictures. Maybe this Pager has the meaning of a click event, such as jumping to a certain web page after clicking. , do this! ? Here you can encapsulate your Adapter data, replace the ImageView with the encapsulated data you define, instantiate a View in the instantiateItem() rewritten in the Adapter, and then return it, because the list of initialized Adapter has the original value in MainActivity Data, then when the user clicks on a pager, extract the information represented by the pager, such as a URL link, etc.

In fact, many apps now use the effect of automatic cycle switching. This effect is nothing more than using a timer Handler. You only need to add the following code:

private Timer mTimer ;	private void startTimer(){		if(mTimer == null){			mTimer = new Timer(true);		}		mTimer.schedule(new TimerTask(){			@Override			public void run() {				mHandler.sendEmptyMessage(0);			}		}, 1000, 4000) ;// 延迟1秒开始执行,循环执行时间是4秒	}		private void stopTimer(){		if(mTimer != null){			mTimer.cancel() ;			mTimer = null ;		}	}		@SuppressLint("HandlerLeak")	Handler mHandler = new Handler(){		public void handleMessage(android.os.Message msg) {			if(msg.what == 0){                 int mViewPagerCurrentIndex = mViewPager.getCurrentItem();                   mViewPagerCurrentIndex = (++mViewPagerCurrentIndex) % mViewPager.getAdapter().getCount() ;                 mViewPager.setCurrentItem(mViewPagerCurrentIndex, true);  			}		};	};
This code provides startTimer() and stopTimer() switches for starting and stopping automatic loop switching. Through these two methods, you can operate more specifically on whether ViewPager needs to automatically switch.

In addition, the automatic switching of ImageSwitcher can also be controlled using this code.

Statement
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
What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

HTML's Purpose: Enabling Web Browsers to Display ContentHTML's Purpose: Enabling Web Browsers to Display ContentMay 03, 2025 am 12:03 AM

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

Explain the importance of using consistent coding style for HTML tags and attributes.Explain the importance of using consistent coding style for HTML tags and attributes.May 01, 2025 am 12:01 AM

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

How to implement multi-project carousel in Bootstrap 4?How to implement multi-project carousel in Bootstrap 4?Apr 30, 2025 pm 03:24 PM

Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...

See all articles

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.