热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

首页dialog广告轮播

先上效果图(点击图片可以跳转相应webview)1.添加Glide依赖implementationcom.github.bumptech.glide:

先上效果图(点击图片可以跳转相应webview)

 

1.添加Glide依赖

implementation 'com.github.bumptech.glide:glide:3.7.0'

2.创建工具类

 2.1创建CircleFlowIndicator工具类

package com.example.test.util;import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;import com.example.test.R;public class CircleFlowIndicator extends View implements FlowIndicator,AnimationListener {private static final int STYLE_STROKE = 0;private static final int STYLE_FILL = 1;private float radius = 4;private float circleSeparation = 2*radius+radius;private float activeRadius = 0.5f;private int fadeOutTime = 0;private final Paint mPaintInactive = new Paint(Paint.ANTI_ALIAS_FLAG);private final Paint mPaintActive = new Paint(Paint.ANTI_ALIAS_FLAG);private ViewFlow viewFlow;private int currentScroll = 0;private int flowWidth = 0;private FadeTimer timer;public AnimationListener animationListener = this;private Animation animation;private boolean mCentered = false;/*** Default constructor* * @param context*/public CircleFlowIndicator(Context context) {super(context);initColors(0xFFFFFFFF, 0xFFFFFFFF, STYLE_FILL, STYLE_STROKE);}/*** The contructor used with an inflater* * @param context* @param attrs*/public CircleFlowIndicator(Context context, AttributeSet attrs) {super(context, attrs);// Retrieve styles attributsTypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CircleFlowIndicator);// Gets the inactive circle type, defaulting to "fill"int activeType = a.getInt(R.styleable.CircleFlowIndicator_activeType,STYLE_FILL);int activeDefaultColor = 0xFFFFFFFF;// Get a custom inactive color if there is oneint activeColor = a.getColor(R.styleable.CircleFlowIndicator_activeColor,activeDefaultColor);// Gets the inactive circle type, defaulting to "stroke"int inactiveType = a.getInt(R.styleable.CircleFlowIndicator_inactiveType, STYLE_STROKE);int inactiveDefaultColor = 0x44FFFFFF;// Get a custom inactive color if there is oneint inactiveColor = a.getColor(R.styleable.CircleFlowIndicator_inactiveColor,inactiveDefaultColor);// Retrieve the radiusradius = a.getDimension(R.styleable.CircleFlowIndicator_radius, 4.0f);circleSeparation = a.getDimension(R.styleable.CircleFlowIndicator_circleSeparation, 2*radius+radius);activeRadius = a.getDimension(R.styleable.CircleFlowIndicator_activeRadius, 0.5f);// Retrieve the fade out timefadeOutTime = a.getInt(R.styleable.CircleFlowIndicator_fadeOut, 0);mCentered = a.getBoolean(R.styleable.CircleFlowIndicator_centered, false);initColors(activeColor, inactiveColor, activeType, inactiveType);}private void initColors(int activeColor, int inactiveColor, int activeType,int inactiveType) {// Select the paint type given the type attrswitch (inactiveType) {case STYLE_FILL:mPaintInactive.setStyle(Style.FILL);break;default:mPaintInactive.setStyle(Style.STROKE);}mPaintInactive.setColor(inactiveColor);// Select the paint type given the type attrswitch (activeType) {case STYLE_STROKE:mPaintActive.setStyle(Style.STROKE);break;default:mPaintActive.setStyle(Style.FILL);}mPaintActive.setColor(activeColor);}/** (non-Javadoc)* * @see android.view.View#onDraw(android.graphics.Canvas)*/@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);int count = 3;if (viewFlow != null) {count = viewFlow.getViewsCount();}//this is the amount the first circle should be offset to make the entire thing centeredfloat centeringOffset = 0;int leftPadding = getPaddingLeft();// Draw stroked circlesfor (int iLoop = 0; iLoop 0) {// Check if we need to create a new timerif (timer == null || timer._run == false) {// Create and start a new timertimer = new FadeTimer();timer.execute();} else {// Reset the current tiemr to 0timer.resetTimer();}}}/*** Counts from 0 to the fade out time and animates the view away when* reached*/private class FadeTimer extends AsyncTask {// The current countprivate int timer = 0;// If we are inside the timing loopprivate boolean _run = true;public void resetTimer() {timer = 0;}@Overrideprotected Void doInBackground(Void... arg0) {while (_run) {try {// Wait for a millisecondThread.sleep(1);// Increment the timertimer++;// Check if we've reached the fade out timeif (timer == fadeOutTime) {// Stop running_run = false;}} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return null;}@Overrideprotected void onPostExecute(Void result) {animation = AnimationUtils.loadAnimation(getContext(),android.R.anim.fade_out);animation.setAnimationListener(animationListener);startAnimation(animation);}}@Overridepublic void onAnimationEnd(Animation animation) {setVisibility(View.GONE);}@Overridepublic void onAnimationRepeat(Animation animation) {}@Overridepublic void onAnimationStart(Animation animation) {}
}

2.2创建,FlowInicator工具类

package com.example.test.util;public interface FlowIndicator extends ViewFlow.ViewSwitchListener {/*** Set the current ViewFlow. This method is called by the ViewFlow when the* FlowIndicator is attached to it.* * @param view*/public void setViewFlow(ViewFlow view);/*** The scroll position has been changed. A FlowIndicator may implement this* method to reflect the current position* * @param h* @param v* @param oldh* @param oldv*/public void onScrolled(int h, int v, int oldh, int oldv);
}

2.3创建ViewFlow工具类

/** Copyright (C) 2011 Patrik Åkerfeldt* * Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/
package com.example.test.util;import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.Scroller;import com.example.test.R;import java.util.ArrayList;
import java.util.LinkedList;/*** * A horizontally scrollable {@link ViewGroup} with items populated from an* {@link Adapter}. The ViewFlow uses a buffer to store loaded {@link View}s in.* The default size of the buffer is 3 elements on both sides of the currently* visible {@link View}, making up a total buffer size of 3 * 2 + 1 = 7. The* buffer size can be changed using the {@code sidebuffer} xml attribute.* * @author http://blog.csdn.net/finddreams*/
public class ViewFlow extends AdapterView {private static final int SNAP_VELOCITY &#61; 1000;private static final int INVALID_SCREEN &#61; -1;private final static int TOUCH_STATE_REST &#61; 0;private final static int TOUCH_STATE_SCROLLING &#61; 1;private LinkedList mLoadedViews;private int mCurrentBufferIndex;private int mCurrentAdapterIndex;private int mSideBuffer &#61; 2;private Scroller mScroller;private VelocityTracker mVelocityTracker;private int mTouchState &#61; TOUCH_STATE_REST;private float mLastMotionX;private int mTouchSlop;private int mMaximumVelocity;private int mCurrentScreen;private int mNextScreen &#61; INVALID_SCREEN;private boolean mFirstLayout &#61; true;private ViewSwitchListener mViewSwitchListener;private Adapter mAdapter;private int mLastScrollDirection;private AdapterDataSetObserver mDataSetObserver;private FlowIndicator mIndicator;private int mLastOrientation &#61; -1;private long timeSpan &#61; 3000;private Handler handler;private OnGlobalLayoutListener orientationChangeListener &#61; new OnGlobalLayoutListener() {&#64;Overridepublic void onGlobalLayout() {getViewTreeObserver().removeGlobalOnLayoutListener(orientationChangeListener);setSelection(mCurrentAdapterIndex);}};/*** Receives call backs when a new {&#64;link View} has been scrolled to.*/public static interface ViewSwitchListener {/*** This method is called when a new View has been scrolled to.* * &#64;param view* the {&#64;link View} currently in focus.* &#64;param position* The position in the adapter of the {&#64;link View} currently in focus.*/void onSwitched(View view, int position);}public ViewFlow(Context context) {super(context);mSideBuffer &#61; 3;init();}public ViewFlow(Context context, int sideBuffer) {super(context);mSideBuffer &#61; sideBuffer;init();}public ViewFlow(Context context, AttributeSet attrs) {super(context, attrs);TypedArray styledAttrs &#61; context.obtainStyledAttributes(attrs,R.styleable.ViewFlow);mSideBuffer &#61; styledAttrs.getInt(R.styleable.ViewFlow_sidebuffer, 3);init();}private void init() {mLoadedViews &#61; new LinkedList();mScroller &#61; new Scroller(getContext());final ViewConfiguration configuration &#61; ViewConfiguration.get(getContext());mTouchSlop &#61; configuration.getScaledTouchSlop();mMaximumVelocity &#61; configuration.getScaledMaximumFlingVelocity();}public void startAutoFlowTimer(){handler &#61; new Handler(){&#64;Overridepublic void handleMessage(Message msg) {snapToScreen((mCurrentScreen&#43;1)%getChildCount());Message message &#61; handler.obtainMessage(0);sendMessageDelayed(message, timeSpan);}};Message message &#61; handler.obtainMessage(0);handler.sendMessageDelayed(message, timeSpan);}public void stopAutoFlowTimer(){if(handler!&#61;null)handler.removeMessages(0);handler &#61; null;}public void onConfigurationChanged(Configuration newConfig) {if (newConfig.orientation !&#61; mLastOrientation) {mLastOrientation &#61; newConfig.orientation;getViewTreeObserver().addOnGlobalLayoutListener(orientationChangeListener);}}public int getViewsCount() {return mSideBuffer;}&#64;Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);final int width &#61; MeasureSpec.getSize(widthMeasureSpec);final int widthMode &#61; MeasureSpec.getMode(widthMeasureSpec);if (widthMode !&#61; MeasureSpec.EXACTLY && !isInEditMode()) {throw new IllegalStateException("ViewFlow can only be used in EXACTLY mode.");}final int heightMode &#61; MeasureSpec.getMode(heightMeasureSpec);if (heightMode !&#61; MeasureSpec.EXACTLY && !isInEditMode()) {throw new IllegalStateException("ViewFlow can only be used in EXACTLY mode.");}// The children are given the same width and height as the workspacefinal int count &#61; getChildCount();for (int i &#61; 0; i mTouchSlop;if (xMoved) {// Scroll if the user moved far enough along the X axismTouchState &#61; TOUCH_STATE_SCROLLING;}if (mTouchState &#61;&#61; TOUCH_STATE_SCROLLING) {// Scroll to follow the motion eventfinal int deltaX &#61; (int) (mLastMotionX - x);mLastMotionX &#61; x;final int scrollX &#61; getScrollX();if (deltaX <0) {if (scrollX > 0) {scrollBy(Math.max(-scrollX, deltaX), 0);}} else if (deltaX > 0) {final int availableToScroll &#61; getChildAt(getChildCount() - 1).getRight()- scrollX - getWidth();if (availableToScroll > 0) {scrollBy(Math.min(availableToScroll, deltaX), 0);}}return true;}break;case MotionEvent.ACTION_UP:if (mTouchState &#61;&#61; TOUCH_STATE_SCROLLING) {final VelocityTracker velocityTracker &#61; mVelocityTracker;velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);int velocityX &#61; (int) velocityTracker.getXVelocity();if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) {// Fling hard enough to move leftsnapToScreen(mCurrentScreen - 1);} else if (velocityX <-SNAP_VELOCITY&& mCurrentScreen mTouchSlop;if (xMoved) {// Scroll if the user moved far enough along the X axismTouchState &#61; TOUCH_STATE_SCROLLING;}if (mTouchState &#61;&#61; TOUCH_STATE_SCROLLING) {// Scroll to follow the motion eventfinal int deltaX &#61; (int) (mLastMotionX - x);mLastMotionX &#61; x;final int scrollX &#61; getScrollX();if (deltaX <0) {if (scrollX > 0) {scrollBy(Math.max(-scrollX, deltaX), 0);}} else if (deltaX > 0) {final int availableToScroll &#61; getChildAt(getChildCount() - 1).getRight()- scrollX - getWidth();if (availableToScroll > 0) {scrollBy(Math.min(availableToScroll, deltaX), 0);}}return true;}break;case MotionEvent.ACTION_UP:if (mTouchState &#61;&#61; TOUCH_STATE_SCROLLING) {final VelocityTracker velocityTracker &#61; mVelocityTracker;velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);int velocityX &#61; (int) velocityTracker.getXVelocity();if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) {// Fling hard enough to move leftsnapToScreen(mCurrentScreen - 1);} else if (velocityX <-SNAP_VELOCITY&& mCurrentScreen // else if (velocityX <-SNAP_VELOCITY
// && mCurrentScreen &#61;&#61; getChildCount() - 1) {
// snapToScreen(0);
// }
// else if (velocityX > SNAP_VELOCITY
// && mCurrentScreen &#61;&#61; 0) {
// snapToScreen(getChildCount() - 1);
// }else {snapToDestination();}if (mVelocityTracker !&#61; null) {mVelocityTracker.recycle();mVelocityTracker &#61; null;}}mTouchState &#61; TOUCH_STATE_REST;if(handler!&#61;null){Message message &#61; handler.obtainMessage(0);handler.sendMessageDelayed(message, timeSpan);}break;case MotionEvent.ACTION_CANCEL:snapToDestination();mTouchState &#61; TOUCH_STATE_REST;}return true;}&#64;Overrideprotected void onScrollChanged(int h, int v, int oldh, int oldv) {super.onScrollChanged(h, v, oldh, oldv);if (mIndicator !&#61; null) {/** The actual horizontal scroll origin does typically not match the* perceived one. Therefore, we need to calculate the perceived* horizontal scroll origin here, since we use a view buffer.*/int hPerceived &#61; h &#43; (mCurrentAdapterIndex - mCurrentBufferIndex)* getWidth();mIndicator.onScrolled(hPerceived, v, oldh, oldv);}}private void snapToDestination() {final int screenWidth &#61; getWidth();final int whichScreen &#61; (getScrollX() &#43; (screenWidth / 2))/ screenWidth;snapToScreen(whichScreen);}private void snapToScreen(int whichScreen) {mLastScrollDirection &#61; whichScreen - mCurrentScreen;if (!mScroller.isFinished())return;whichScreen &#61; Math.max(0, Math.min(whichScreen, getChildCount() - 1));mNextScreen &#61; whichScreen;final int newX &#61; whichScreen * getWidth();final int delta &#61; newX - getScrollX();mScroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta) * 2);invalidate();}&#64;Overridepublic void computeScroll() {if (mScroller.computeScrollOffset()) {scrollTo(mScroller.getCurrX(), mScroller.getCurrY());postInvalidate();} else if (mNextScreen !&#61; INVALID_SCREEN) {mCurrentScreen &#61; Math.max(0,Math.min(mNextScreen, getChildCount() - 1));mNextScreen &#61; INVALID_SCREEN;postViewSwitched(mLastScrollDirection);}}/*** Scroll to the {&#64;link View} in the view buffer specified by the index.* * &#64;param indexInBuffer* Index of the view in the view buffer.*/private void setVisibleView(int indexInBuffer, boolean uiThread) {mCurrentScreen &#61; Math.max(0,Math.min(indexInBuffer, getChildCount() - 1));int dx &#61; (mCurrentScreen * getWidth()) - mScroller.getCurrX();mScroller.startScroll(mScroller.getCurrX(), mScroller.getCurrY(), dx,0, 0);if(dx &#61;&#61; 0)onScrollChanged(mScroller.getCurrX() &#43; dx, mScroller.getCurrY(), mScroller.getCurrX() &#43; dx, mScroller.getCurrY());if (uiThread)invalidate();elsepostInvalidate();}/*** Set the listener that will receive notifications every time the {code* ViewFlow} scrolls.* * &#64;param l* the scroll listener*/public void setOnViewSwitchListener(ViewSwitchListener l) {mViewSwitchListener &#61; l;}&#64;Overridepublic Adapter getAdapter() {return mAdapter;}&#64;Overridepublic void setAdapter(Adapter adapter) {setAdapter(adapter, 0);}public void setAdapter(Adapter adapter, int initialPosition) {if (mAdapter !&#61; null) {mAdapter.unregisterDataSetObserver(mDataSetObserver);}mAdapter &#61; adapter;if (mAdapter !&#61; null) {mDataSetObserver &#61; new AdapterDataSetObserver();mAdapter.registerDataSetObserver(mDataSetObserver);}if (mAdapter &#61;&#61; null || mAdapter.getCount() &#61;&#61; 0)return;setSelection(initialPosition); }&#64;Overridepublic View getSelectedView() {return (mCurrentBufferIndex recycleViews &#61; new ArrayList();View recycleView;while (!mLoadedViews.isEmpty()) {recycleViews.add(recycleView &#61; mLoadedViews.remove());detachViewFromParent(recycleView);}View currentView &#61; makeAndAddView(position, true,(recycleViews.isEmpty() ? null : recycleViews.remove(0)));mLoadedViews.addLast(currentView);for(int offset &#61; 1; mSideBuffer - offset >&#61; 0; offset&#43;&#43;) {int leftIndex &#61; position - offset;int rightIndex &#61; position &#43; offset;if(leftIndex >&#61; 0)mLoadedViews.addFirst(makeAndAddView(leftIndex, false,(recycleViews.isEmpty() ? null : recycleViews.remove(0))));if(rightIndex 0) { // to the rightmCurrentAdapterIndex&#43;&#43;;mCurrentBufferIndex&#43;&#43;;// if(direction > 1) {
// mCurrentAdapterIndex &#43;&#61; mAdapter.getCount() - 2;
// mCurrentBufferIndex &#43;&#61; mAdapter.getCount() - 2;
// }View recycleView &#61; null;// Remove view outside buffer rangeif (mCurrentAdapterIndex > mSideBuffer) {recycleView &#61; mLoadedViews.removeFirst();detachViewFromParent(recycleView);// removeView(recycleView);mCurrentBufferIndex--;}// Add new view to bufferint newBufferIndex &#61; mCurrentAdapterIndex &#43; mSideBuffer;if (newBufferIndex // mCurrentAdapterIndex -&#61; mAdapter.getCount() - 2;
// mCurrentBufferIndex -&#61; mAdapter.getCount() - 2;
// }View recycleView &#61; null;// Remove view outside buffer rangeif (mAdapter.getCount() - 1 - mCurrentAdapterIndex > mSideBuffer) {recycleView &#61; mLoadedViews.removeLast();detachViewFromParent(recycleView);}// Add new view to bufferint newBufferIndex &#61; mCurrentAdapterIndex - mSideBuffer;if (newBufferIndex > -1) {mLoadedViews.addFirst(makeAndAddView(newBufferIndex, false,recycleView));mCurrentBufferIndex&#43;&#43;;}}requestLayout();setVisibleView(mCurrentBufferIndex, true);if (mIndicator !&#61; null) {mIndicator.onSwitched(mLoadedViews.get(mCurrentBufferIndex),mCurrentAdapterIndex);}if (mViewSwitchListener !&#61; null) {mViewSwitchListener.onSwitched(mLoadedViews.get(mCurrentBufferIndex),mCurrentAdapterIndex);}}private View setupChild(View child, boolean addToEnd, boolean recycle) {LayoutParams p &#61; (LayoutParams) child.getLayoutParams();if (p &#61;&#61; null) {p &#61; new AbsListView.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT, 0);}if (recycle)attachViewToParent(child, (addToEnd ? -1 : 0), p);elseaddViewInLayout(child, (addToEnd ? -1 : 0), p, true);return child;}private View makeAndAddView(int position, boolean addToEnd, View convertView) {View view &#61; mAdapter.getView(position, convertView, this);return setupChild(view, addToEnd, convertView !&#61; null);}class AdapterDataSetObserver extends DataSetObserver {&#64;Overridepublic void onChanged() {View v &#61; getChildAt(mCurrentBufferIndex);if (v !&#61; null) {for (int index &#61; 0; index }

2.4创建ProgressWebView工具类&#xff08;点击广告要跳转的webview&#xff09;

package com.example.test.util;import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.webkit.WebView;
import android.widget.ProgressBar;import com.example.test.R;/*** &#64;Description: 带进度条的WebView* &#64;author http://blog.csdn.net/finddreams*/
&#64;SuppressWarnings("deprecation")
public class ProgressWebView extends WebView {private ProgressBar progressbar;public ProgressWebView(Context context, AttributeSet attrs) {super(context, attrs);progressbar &#61; new ProgressBar(context, null,android.R.attr.progressBarStyleHorizontal);progressbar.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,10, 0, 0));Drawable drawable &#61; context.getResources().getDrawable(R.drawable.progress_bar_states);progressbar.setProgressDrawable(drawable);addView(progressbar);// setWebViewClient(new WebViewClient(){});setWebChromeClient(new WebChromeClient());//是否支持缩放getSettings().setSupportZoom(true);getSettings().setBuiltInZoomControls(true); }public class WebChromeClient extends android.webkit.WebChromeClient {&#64;Overridepublic void onProgressChanged(WebView view, int newProgress) {if (newProgress &#61;&#61; 100) {progressbar.setVisibility(GONE);} else {if (progressbar.getVisibility() &#61;&#61; GONE)progressbar.setVisibility(VISIBLE);progressbar.setProgress(newProgress);}super.onProgressChanged(view, newProgress);}}&#64;Overrideprotected void onScrollChanged(int l, int t, int oldl, int oldt) {LayoutParams lp &#61; (LayoutParams) progressbar.getLayoutParams();lp.x &#61; l;lp.y &#61; t;progressbar.setLayoutParams(lp);super.onScrollChanged(l, t, oldl, oldt);}
}

3.创建BaseWebActivity&#xff08;及得在配置文件注册activity&#xff09;

package com.example.test.activity;import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;import com.example.test.R;
import com.example.test.base.BaseApplication;
import com.example.test.util.ProgressWebView;/*** &#64;Description:WebView界面&#xff0c;带自定义进度条显示* &#64;author http://blog.csdn.net/finddreams*/
public class BaseWebActivity extends Activity {private static String TAG &#61; BaseWebActivity.class.getSimpleName() &#43; "&#61;&#61;&#61;";protected ProgressWebView mWebView;&#64;Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_baseweb);BaseApplication.getApp().addActivity(this);if (Build.VERSION.SDK_INT >&#61; Build.VERSION_CODES.LOLLIPOP) {Window window &#61; getWindow();// 有些情况下需要先清除透明flagwindow.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));}mWebView &#61; (ProgressWebView) findViewById(R.id.baseweb_webview);mWebView.getSettings().setJavascriptEnabled(true);initData();}protected void initData() {Intent intent &#61; getIntent();Bundle bundle &#61; intent.getExtras();String urls &#61; bundle.getString("url");mWebView.loadUrl(urls);mWebView.getSettings().setJavascriptEnabled(true);mWebView.getSettings().setAppCacheEnabled(true);//设置 缓存模式  mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);// 开启 DOM storage API 功能  mWebView.getSettings().setDomStorageEnabled(true);mWebView.setWebViewClient(new WebViewClient(){&#64;Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {// view.loadUrl(url);return super.shouldOverrideUrlLoading(view, url);}});}&#64;Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {try{if (keyCode &#61;&#61; KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {mWebView.goBack();// 返回前一个页面return true;}else{BaseApplication.getApp().finishActivity(this);finish();}}catch (Exception e){}return super.onKeyDown(keyCode, event);}&#64;Overrideprotected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();mWebView &#61; null;BaseApplication.getApp().finishActivity(this);}}

3.drawable相关文件

3.1advertising_bg.xml



3.2progress_bar_states.xml



4.图片适配器ImagePagerAdapter

/** Copyright 2014 trinea.cn All right reserved. This software is the confidential and proprietary information of* trinea.cn ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in* accordance with the terms of the license agreement you entered into with trinea.cn.*/
package com.example.test.adapter;import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;import com.bumptech.glide.Glide;
import com.example.test.R;
import com.example.test.activity.BaseWebActivity;import java.util.List;/*** &#64;author http://blog.csdn.net/finddreams* &#64;Description: 图片适配器*/
public class ImagePagerAdapter extends BaseAdapter {private List imageIdList;private List linkUrlArray;private int size;private boolean isInfiniteLoop;private Dialog dialogs;public ImagePagerAdapter(Context context, List imageIdList,List urllist, Dialog dialogs) {this.imageIdList &#61; imageIdList;if (imageIdList !&#61; null) {this.size &#61; imageIdList.size();}this.linkUrlArray &#61; urllist;isInfiniteLoop &#61; false;this.dialogs &#61; dialogs;}&#64;Overridepublic int getCount() {// Infinite loopreturn isInfiniteLoop ? Integer.MAX_VALUE : imageIdList.size();}/*** get really position** &#64;param position* &#64;return*/private int getPosition(int position) {return isInfiniteLoop ? position % size : position;}&#64;Overridepublic View getView(final int position, View view, ViewGroup container) {final ViewHolder holder;if (view &#61;&#61; null) {holder &#61; new ViewHolder();view &#61; holder.imageView &#61; new ImageView(container.getContext());holder.imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));holder.imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);holder.imageView.setBackgroundResource(R.drawable.advertising_bg);view.setTag(holder);} else {holder &#61; (ViewHolder) view.getTag();}//TODO:view的布局需要添加容器&#xff0c;glide对需要imageview不被设置tagContext context &#61; holder.imageView.getContext();Glide.with(context).load(this.imageIdList.get(getPosition(position))).error(R.mipmap.loaderror).placeholder(R.mipmap.loaderror).fallback(R.mipmap.loaderror).into(holder.imageView);
// Glide.with(context)
// .load(this.imageIdList.get(getPosition(position))).fitCenter().into(holder.imageView);
// imageLoader.displayImage(
// (String) this.imageIdList.get(getPosition(position)),
// holder.imageView, options);holder.imageView.setOnClickListener(new OnClickListener() {&#64;Overridepublic void onClick(View arg0) {String url &#61; linkUrlArray.get(ImagePagerAdapter.this.getPosition(position));Bundle bundle &#61; new Bundle();bundle.putString("url", url);Intent intent &#61; new Intent(arg0.getContext(), BaseWebActivity.class);intent.putExtras(bundle);arg0.getContext().startActivity(intent);dialogs.dismiss();}});return view;}private static class ViewHolder {ImageView imageView;}/*** &#64;return the isInfiniteLoop*/public boolean isInfiniteLoop() {return isInfiniteLoop;}/*** &#64;param isInfiniteLoop the isInfiniteLoop to set*/public ImagePagerAdapter setInfiniteLoop(boolean isInfiniteLoop) {this.isInfiniteLoop &#61; isInfiniteLoop;return this;}&#64;Overridepublic Object getItem(int arg0) {// TODO Auto-generated method stubreturn arg0;}&#64;Overridepublic long getItemId(int arg0) {// TODO Auto-generated method stubreturn arg0;}}

5.相关layout文件

5.1activity_main_advertising.xml


5.2activity_baseweb.xml


6.value相关文件

6.1arrt.xml




6.2dimens.xml

8dp300dp400dp

6.3ids.xml




6.4设置完ids文件后再application的oncreate方法中添加下面代码

ViewTarget.setTagId(R.id.tag_glide);

7.主页Activity

/*** 广告相关*/
private ViewFlow mViewFlow;
private CircleFlowIndicator mFlowIndicator;
private ArrayList imageUrlList &#61; new ArrayList();
private ArrayList linkUrlArray &#61; new ArrayList();
private LayoutInflater inflater;
private RelativeLayout layout;
private ImageView iv_close;
private Dialog dialogs;

&#64;Override
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);BaseApplication.getApp().addActivity(this);initView();initData();
}

/*** 初始化控件*/
private void initView() {

/*** 广告相关*/
inflater &#61; LayoutInflater.from(MainActivity.this);
layout &#61; (RelativeLayout) inflater.inflate(R.layout.activity_main_advertising, null);
iv_close &#61; (ImageView) layout.findViewById(R.id.iv_close);
mViewFlow &#61; (ViewFlow) layout.findViewById(R.id.viewflow);
mViewFlow.setOnItemClickListener(new AdapterView.OnItemClickListener() {&#64;Overridepublic void onItemClick(AdapterView parent, View view, int position, long id) {dialogs.dismiss();}
});
mFlowIndicator &#61; (CircleFlowIndicator) layout.findViewById(R.id.viewflowindic);
iv_close.setOnClickListener(new View.OnClickListener() {&#64;Overridepublic void onClick(View view) {dialogs.dismiss();}
});

/*** 初始化数据*/
private void initData() {

//广告相关
linkUrlArray.add("http://www.baidu.com");
linkUrlArray.add("https://www.csdn.net/");
linkUrlArray.add("https://www.oschina.net/");imageUrlList.add("http://cn.bing.com/az/hprichbg/rb/Dongdaemun_ZH-CN10736487148_1920x1080.jpg");
imageUrlList.add("http://pic.people.com.cn/NMediaFile/2019/0610/MAIN201906101623000225736784754.jpg");
imageUrlList.add("http://www.gregscott.com/gjs_2007_spring/hummingbird/20070311_1948_100_0560.rufous_humminbird.jpg");
initBanner(imageUrlList);

}

private void showDialog() {dialogs.setCanceledOnTouchOutside(false);//dialog弹出后会点击屏幕&#xff0c;dialog不消失&#xff1b;点击物理返回键dialog消失dialogs.show();dialogs.getWindow().setContentView(layout);dialogs.getWindow().setBackgroundDrawableResource(R.color.transparent);
}/*** &#64;param imageUrlList 广告图片url list*/
private void initBanner(ArrayList imageUrlList) {dialogs &#61; new AlertDialog.Builder(MainActivity.this).create();mViewFlow.setAdapter(new ImagePagerAdapter(this, imageUrlList,linkUrlArray, dialogs).setInfiniteLoop(true));mViewFlow.setmSideBuffer(imageUrlList.size()); // 实际图片张数&#xff0c;mViewFlow.setFlowIndicator(mFlowIndicator, imageUrlList.size());mViewFlow.setTimeSpan(3500);mViewFlow.setSelection(imageUrlList.size() * 1000); // 设置初始位置if (imageUrlList.size() > 1) {//大于1页广告开启轮播mViewFlow.startAutoFlowTimer(); // 启动自动播放} else {mFlowIndicator.setVisibility(View.GONE);}showDialog();
}

}

 

 

推荐阅读
  • Android自定义控件绘图篇之Paint函数大汇总
    本文介绍了Android自定义控件绘图篇中的Paint函数大汇总,包括重置画笔、设置颜色、设置透明度、设置样式、设置宽度、设置抗锯齿等功能。通过学习这些函数,可以更好地掌握Paint的用法。 ... [详细]
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
    原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • Google Play推出全新的应用内评价API,帮助开发者获取更多优质用户反馈。用户每天在Google Play上发表数百万条评论,这有助于开发者了解用户喜好和改进需求。开发者可以选择在适当的时间请求用户撰写评论,以获得全面而有用的反馈。全新应用内评价功能让用户无需返回应用详情页面即可发表评论,提升用户体验。 ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • HTML学习02 图像标签的使用和属性
    本文介绍了HTML中图像标签的使用和属性,包括定义图像、定义图像地图、使用源属性和替换文本属性。同时提供了相关实例和注意事项,帮助读者更好地理解和应用图像标签。 ... [详细]
  • 标题: ... [详细]
  • 本文介绍了一些Java开发项目管理工具及其配置教程,包括团队协同工具worktil,版本管理工具GitLab,自动化构建工具Jenkins,项目管理工具Maven和Maven私服Nexus,以及Mybatis的安装和代码自动生成工具。提供了相关链接供读者参考。 ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • EzPP 0.2发布,新增YAML布局渲染功能
    EzPP发布了0.2.1版本,新增了YAML布局渲染功能,可以将YAML文件渲染为图片,并且可以复用YAML作为模版,通过传递不同参数生成不同的图片。这个功能可以用于绘制Logo、封面或其他图片,让用户不需要安装或卸载Photoshop。文章还提供了一个入门例子,介绍了使用ezpp的基本渲染方法,以及如何使用canvas、text类元素、自定义字体等。 ... [详细]
  • 本文整理了Java中org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc.getTypeInfo()方法的一些代码示例,展 ... [详细]
author-avatar
牧高风_457
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有