• Android中使用ViewPage进行广告轮播测试代码


    activity_main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="200dp" />
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@id/viewpager"
            android:background="#33000000"
            android:orientation="vertical"
            android:padding="5dp">
    
            <TextView
                android:id="@+id/tv_image_description"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="广告测试"
                android:textColor="@android:color/white" />
    
            <LinearLayout
                android:id="@+id/ll_point_group"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="5dp"
                android:orientation="horizontal"/>
        </LinearLayout>
    </RelativeLayout>

    point_background.xml

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/point_bg_enable" android:state_enabled="true"/>
        <item android:drawable="@drawable/point_bg_normal" android:state_enabled="false"/>
    </selector>

    point_bg_enable.xml

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

    point_bg_normal.xml

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

    MainActivity

    package cn.seanlou.viewpagedemo;
    
    import android.app.Activity;
    import android.graphics.drawable.GradientDrawable;
    import android.os.Handler;
    import android.os.Message;
    import android.os.SystemClock;
    import android.provider.ContactsContract;
    import android.support.v4.view.PagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    import java.util.List;
    
    
    public class MainActivity extends Activity {
        private ViewPager mViewPager;
        private TextView tvDescription;
        private LinearLayout llPointGroup;
        /**
         * 广告条正下方的标语
         */
        private String[] imageDescriptionArray = {"广告1", "广告2", "广告3", "广告4", "广告5"};
        /**
         * 记录上一次点的位置,默认为0
         */
        private int previousPointEnale = 0;
        private List<ImageView> mImageList = new ArrayList<ImageView>();
        int[] imageIds = new int[]{R.mipmap.a, R.mipmap.b, R.mipmap.c, R.mipmap.d, R.mipmap.e};
        /**
         * 记录是否停止循环播放
         */
        private boolean isStop = false;
        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
                super.handleMessage(msg);
            }
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            findView();
            testAD();
        }
    
        /**
         * 测试广告
         */
        private void testAD() {
            // TODO:广告
            mImageList.clear();
            llPointGroup.removeAllViews();
            // 初始化广告条资源
            for (final int id : imageIds) {
                ImageView mImageView = new ImageView(this);
                mImageView.setBackgroundResource(id);
                mImageView.setOnClickListener(new View.OnClickListener() {
    
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this, id + "", Toast.LENGTH_SHORT).show();
                    }
                });
                mImageList.add(mImageView);
    
                // 初始化广告条正下方的"点"
                View dot = new View(this);
                dot.setBackgroundResource(R.drawable.point_background);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(5, 5);
                params.leftMargin = 10;
                dot.setLayoutParams(params);
                dot.setEnabled(false);
                llPointGroup.addView(dot);
            }
    
            mViewPager.setAdapter(new ADsAdapter());
            // 设置广告条跳转时,广告语和状态语的变化
            mViewPager.setOnPageChangeListener(new MyOnPageChangeListener());
            // 初始化广告条,当前索引Integer.MAX_VALUE的一半
            int index = (Integer.MAX_VALUE / 2) - (Integer.MAX_VALUE / 2 % mImageList.size());
            mViewPager.setCurrentItem(index); // 设置当前选中的Page,会触发onPageChangListener.onPageSelected方法
        }
    
        private void findView() {
            mViewPager = (ViewPager) findViewById(R.id.viewpager);
            tvDescription = (TextView) findViewById(R.id.tv_image_description);
            llPointGroup = (LinearLayout) findViewById(R.id.ll_point_group);
        }
    
        /**
         * 滑动监听
         */
        private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
    
            @Override
            public void onPageScrolled(int i, float v, int i2) {
    
            }
    
            @Override
            public void onPageSelected(int i) {
                //获取新的位置
                int newPosition = i % imageDescriptionArray.length;
                //设置广告标语
                tvDescription.setText(imageDescriptionArray[newPosition]);
                //消除上一次的状态点
                llPointGroup.getChildAt(previousPointEnale).setEnabled(false);
                //设置当前的状态点
                llPointGroup.getChildAt(newPosition).setEnabled(true);
                //记录新的位置
                previousPointEnale = newPosition;
            }
    
            @Override
            public void onPageScrollStateChanged(int i) {
    
            }
        }
    
        private class ADsAdapter extends PagerAdapter {
            @Override
            public int getCount() {
                // 将viewpager页数设置成Integer.MAX_VALUE,可以模拟无限循环
                return Integer.MAX_VALUE;
            }
    
            /**
             * 复用对象 true 复用view false 复用的是Object
             */
            @Override
            public boolean isViewFromObject(View view, Object o) {
                return view == o;
            }
    
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(mImageList.get(position % mImageList.size()));
                return mImageList.get(position % mImageList.size());
            }
    
            /**
             * 销毁对象
             *
             * @param position 被销毁对象的索引位置
             */
            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mImageList.get(position % mImageList.size()));
            }
        }
    
        @Override
        public void onResume() {
            // 开启子线程,让广告条以3秒的频率循环播放
            isStop = false;
            new Thread(new Runnable() {
    
                @Override
                public void run() {
    
                    while (!isStop) {
                        SystemClock.sleep(3000);
                        handler.sendEmptyMessage(-1);
                    }
                }
            }).start();
            super.onResume();
        }
    
        @Override
        public void onPause() {
            // FragmentHome销毁时候,关闭循环播放
            isStop = true;
            super.onPause();
        }
    }
  • 相关阅读:
    如何使用NuGet package .nupkg文件?
    利用Z.Expressions.Eval表达式求值
    表达式实现填写“阶段标记”属性
    NX导入DWG失败
    简单工厂模式(Simple Factory Pattern)
    电脑装系统蓝屏未解决
    idea intellij 配置总结
    poiexcel 笔记
    Springboot
    Springboot--maven命令子模块单独打包
  • 原文地址:https://www.cnblogs.com/louguanyang/p/4424242.html
Copyright © 2020-2023  润新知