Automatic switching (sliding) of ViewPager pictures

Effect display: slide pictures, text and dots at the same time

I. using custom controls

There is a jar package in the libs directory of Android: android-support-v4 Jar, which contains the custom control ViewPager

Use this control in a layout file:

1. Wrap the ViewPager control with a frame layout

2. Add LinearLayout (including text and dots) on the ViewPager

3. Use LinearLayout to include five dots

4. Setting the status selector for small dots: using shape

Ordinary dot

Display dot

2, Effect in Activity

1. Fill data:

Create a collection and array of pictures, text, and dots, respectively

2. Initialize the get control

① Set title

② Set adapter for ViewPager [inherited from PagerAdapter]: add data and delete data in the adapter

Add data: viewpager addView(..)

Delete data: viewpage removeView(…)

 

③ set the listener when the ViewPager changes to realize the effect that the dots and text change with the picture at the same time

There are three states:

onPageScrollStateChanged: indicates whether it is in a sliding (changed) state

onPageScrolled: the state when the page slides

onPageSelected: the state when the page is changed

Update processing text and dots in onpageselected:

Text: update the title, that is, the displayed text

Dot:

Define global variable: record the position of the dot on the previous page

Update the display of dots: set the status of the current latest dots as the display status [set the picture as the style when displayed in the status selector]

Set the status of dots before update to normal status

Assign the state of the latest dot to the dot before update

3. Set automatic change page

Tips:

When the page can be displayed, the onStart method is executed

When not displayed, the onStop method is executed

Timer is sensitive when it is based on the system time. When the system time changes, it will change

Therefore, use Executors to create a single thread pool timer

1. Timers for creating a one-way pool through Executors:

Even if the operation is performed through this timer

        scheduledExecutor = Executors.newSingleThreadScheduledExecutor();

        

Parameters:

① tasks performed

② delay time

③ interval time

④ unit of execution time

2. Tasks performed: create a Task task

Switch pictures

Send message notification interface update (just send an empty message)

3. Create a Handler to receive messages

In the handleMessage method, set the current entry through viewPager, that is, specify the display of the current page

4. Stop switching

Stop switching pictures in onStop method by stopping the timer (shutdown method)

Tips: how to realize infinite loop playback:

When getting each page, use position% images In the form of size (), when the last page is reached, it will automatically return to the first interface for replay

Note that you need to set the return value of the getCount method in the adapter to the maximum value (MAX_VALUE) of Integer to achieve the effect of infinite loop

public class MainActivity extends Activity {

	private List<ImageView> imageViews;
	private String[] titles;
	private List<View> dots;
	private ViewPager vp;
	private TextView tv_title;
	private MyPagerAdapter adapter;
	private int currentItem;
	private int oldPosition;
	private ScheduledExecutorService scheduledExecutor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initData();
		initView();
	}

	// Initialization data, filling
	private void initData() {
		// picture
		int[] imageIDs = { R.drawable.a, R.drawable.b, R.drawable.c,
				R.drawable.d, R.drawable.e };
		imageViews = new ArrayList<ImageView>();
		for (int i = 0; i < imageIDs.length; i++) {
			ImageView imageView = new ImageView(getApplicationContext());
			imageView.setImageResource(imageIDs[i]);
			imageViews.add(imageView);
		}
		// written words
		titles = new String[] { "If Gong Li is not vulgar, I can't be vulgar", "The tree is back! Then sing classic old songs and lead thousands of people to sing a chorus",
				"How to upgrade Beijing films", "letv  TV Edition delivery", "The anti killing of hot-blooded losers" };

		// Dot
		dots = new ArrayList<View>();
		dots.add(findViewById(R.id.dot_0));
		dots.add(findViewById(R.id.dot_1));
		dots.add(findViewById(R.id.dot_2));
		dots.add(findViewById(R.id.dot_3));
		dots.add(findViewById(R.id.dot_4));
	}

	// Initialize control
	private void initView() {
		// Locate the viewpr control
		vp = (ViewPager) findViewById(R.id.vp);
		
		// Locate the text box and set the title
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_title.setText(titles[0]);
		
		// Set the adapter for viewpager
		adapter = new MyPagerAdapter();
		vp.setAdapter(adapter);
		// Set the listener for the page change of the viewpager
		vp.setOnPageChangeListener(new MyOnPageChangeListener());

	}

	// Page change listener for viewpager
	private class MyOnPageChangeListener implements OnPageChangeListener {

		//Update the page when the page changes
		public void onPageSelected(int position) {
			currentItem = position;
			//written words
			tv_title.setText(titles[position%imageViews.size()]);
			
			//Dot
			dots.get(position%imageViews.size()).setBackgroundResource(R.drawable.dot_focused);
			dots.get(oldPosition%imageViews.size()).setBackgroundResource(R.drawable.dot_normal);
			
			oldPosition = position;

		}

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

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	// Adapter for viewpager
	private class MyPagerAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			//In order to achieve unlimited automatic switching, set the maximum value
			return Integer.MAX_VALUE;
		}

		//Delete data
		public void destroyItem(ViewGroup container, int position, Object object) {
			vp.removeView(imageViews.get(position%imageViews.size()));
		}

		//Add data
		public Object instantiateItem(View container, int position) {
			vp.addView(imageViews.get(position%imageViews.size()));
			return imageViews.get(position%imageViews.size());
		}

		//TODO ?
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0==arg1;
		}
	}

	//Automatic switching at the beginning
	protected void onStart() {
		super.onStart();
		//Create one-way pool timer
		scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
		scheduledExecutor.scheduleAtFixedRate(new MyPagerTask(), 2, 2, TimeUnit.SECONDS);
	}
	
	//When stopping, stop switching
	protected void onStop() {
		super.onStop();
		scheduledExecutor.shutdown();
		scheduledExecutor = null;
	}
	
	private class MyPagerTask implements Runnable{

		public void run() {
			currentItem ++;
			handler.sendEmptyMessage(0);
		}
		
	}
	
	//Receive messages and set the current interface
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			vp.setCurrentItem(currentItem);
		}
	};
	
}

Keywords: Java Android webview

Added by zaki on Thu, 16 Dec 2021 02:52:46 +0200