Android realizes the display effect of carousel pictures
- 2021-11-01 04:43:21
- OfStack
In this article, we share the display of Android carousel pictures for your reference. The specific contents are as follows
Implementation logic
1. Create an XML layout file and use ViewPager to complete the carousel picture
2. Initialize the ViewPager control, then set the adapter for the control, and create the adapter to implement the four methods inside
3.4 Methods are getCount isViewFromObject instantiateItem destroyItem
4. In the onCreat method, the picture resource is loaded, and the picture ID is stored in the collection, so that the picture can be displayed in the page. (The reason why the picture can be displayed in the page is that the picture elements in the collection are obtained in the instantiateItem method in the adapter)
5. Text display at the bottom of the picture: The reason why there is text at the bottom of the picture can be initialized by tv_desc. setText (descs [position]) in the onPageSelected method in the ViewPager listener; In this way, the text can be switched with the follower picture
6. Switching small dots below the text: Set an Linlayout layout in XML layout, and then set small dots in onCreat method, through LinearLayout. LayoutParams layoutParams = new LinearLayout. LayoutParams (10, 10); The method of introducing small dots (the specific code can refer to the initDot method below)
7. To make the dot switch as the page switches, you can define the changeDots method below, and let this method be called in the onPageSelected method in the listener
8. The realization of unlimited carousel of pictures: the return value of getCount in the adapter can be set to a very large value, and position position = position% imageResIds. length in the instantiateItem method; Prevent the index from crossing the boundary, so that the picture can be broadcast indefinitely. However, there is another problem at this time, that is, the right side can be broadcast indefinitely, but the left side cannot be broadcast indefinitely. The solution to this problem is to set the currently selected entry viewPager. setCurrentItem (count/2) in the onCreat method; In this way, both sides can realize unlimited carousel
9. The processing of automatic picture switching: Using handler mechanism to realize the delay update of the page, at the same time, in order to prevent memory overflow, it is necessary to send messages when the page is visible, that is, in onStart method of activity, and delete messages when the page disappears, that is, in onStop method
Layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.a2_.MainActivity">
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="250dp">
</android.support.v4.view.ViewPager>
<LinearLayout
android:orientation="vertical"
android:gravity="center"
android:background="#66000000"
android:layout_alignBottom="@id/vp"
android:layout_width="match_parent"
android:layout_height="50dp">
<TextView
android:id="@+id/desc"
android:text=" Descriptive text "
android:textColor="#ffffff"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:id="@+id/layout_dot"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Core code
package com.example.a2_;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final int UPDATE_ITEM = 1;
private ArrayList<ImageView> imageViews = new ArrayList<>();
private int[] imageResIds = {R.mipmap.icon_1, R.mipmap.icon_2, R.mipmap.icon_3,
R.mipmap.icon_4, R.mipmap.icon_5};
private String[] descs = {" Stick to your dreams ", " I believe I am a dark horse ", " Dark Horse Open Class ", "Google/IO", " Relaxed 1w+"};
private ViewPager viewPager;
private TextView tv_desc;
private LinearLayout layout_dot;
private int count = 10000000;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_ITEM:
upDataItem();
break;
}
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize control
viewPager = (ViewPager) findViewById(R.id.vp);
tv_desc = (TextView) findViewById(R.id.desc);
layout_dot = (LinearLayout) findViewById(R.id.layout_dot);
// To viewPager Setting adapter
viewPager.setAdapter(new MyPagerAdapter());
// Right viewPager Set up the listener
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// Triggered time when the page scrolls
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
// Method that triggers when the page is selected
@Override
public void onPageSelected(int position) {
// Right position Process
position = position % imageViews.size();
// When the page is selected , Change the description text
tv_desc.setText(descs[position]);
changeDots(position);
}
// Event triggered when the page state scroll state changes
@Override
public void onPageScrollStateChanged(int state) {
// When the idle state of the page is changed
if (state == viewPager.SCROLL_STATE_IDLE) {
handler.sendEmptyMessageDelayed(UPDATE_ITEM, 3000);
} else {
handler.removeMessages(UPDATE_ITEM);
}
}
});
// Initialize a picture
initImage();
// Initializes the dot below the text
initDot();
// When the page is loaded, , Default yield 1 Text is loaded out
// initDescFirst();
// So that both sides can rotate indefinitely
viewPager.setCurrentItem(count / 2);
// Update when page loads
upDataItem();
}
private void upDataItem() {
int index = viewPager.getCurrentItem();
viewPager.setCurrentItem(++index);
handler.sendEmptyMessageDelayed(UPDATE_ITEM, 3000);
}
// Select the corresponding origin
private void changeDots(int position) {
// Restore all dots to white first
for (int i = 0; i < layout_dot.getChildCount(); i++) {
View view = layout_dot.getChildAt(i);
view.setSelected(false);
}
// Gets the currently selected entry Set to selected status
layout_dot.getChildAt(position).setSelected(true);
}
// Initializes the dot below the text
private void initDot() {
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(10, 10);
layoutParams.setMargins(4, 4, 4, 4);
for (int i = 0; i < imageViews.size(); i++) {
View view = new View(this);
view.setBackgroundResource(R.drawable.seletor_dot);
view.setLayoutParams(layoutParams);
layout_dot.addView(view);
}
}
// When the page is loaded, , Default yield 1 Text is loaded out
private void initDescFirst() {
tv_desc.setText(descs[0]);
changeDots(0);
}
// Add a picture , Prepare 1 A ImageView Set , Used to give instantiateItem Add to Page
private void initImage() {
for (int i = 0; i < imageResIds.length; i++) {
// Create a ImageView Object
ImageView imageView = new ImageView(getApplicationContext());
imageView.setImageResource(imageResIds[i]);
imageViews.add(imageView);
}
}
private class MyPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return count;
}
@Override
public boolean isViewFromObject(View view, Object object) {
// Judge this view Is it through instantiateItem Created
return view == object;
}
// Used to create entries
@Override
public Object instantiateItem(ViewGroup container, int position) {
position = position % imageResIds.length;
// Get an entry
ImageView imageView = imageViews.get(position);
container.addView(imageView);
return imageView;
}
// Used to destroy entries ,, And at most, it will create 3 Items , Extra entries will be destroyed
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Destroy the created entry
container.removeView((View) object);
}
}
@Override
protected void onStart() {
super.onStart();
// When the page is displayed, , Update carousel chart
handler.sendEmptyMessageDelayed(UPDATE_ITEM, 3000);
}
@Override
protected void onStop() {
super.onStop();
// When the page is not visible , Stop updating
handler.removeCallbacksAndMessages(null);
}
}