Android 구성 요소 banner 좌우 슬라이더 효과 구현
1.원리
아래 그림 참조.전체 구성 요 소 는 FrameLayout 입 니 다.그 안에 두 개의 view 가 있 습 니 다.첫 번 째 는 LinearLayout 입 니 다.4 개(또는 여러 개)가 미 끄 러 질 수 있 는 view 를 실 었 습 니 다.그림 에서 녹색 배경 부분 을 보십시오.두 번 째 는 RelativeLayout 입 니 다.그 밑 에 LinearLayout 를 설치 하고 LinearLayout 내부 에 몇 개의 작은 원점 을 설치 하여 현재 화면의 색인 을 표시 합 니 다.제스처 검 사 는 Gesture Detector 를 사 용 했 고 OnGesture Listener 인 터 페 이 스 를 실현 했다.미끄럼 속 도 를 조절 하기 위해 Scroller 탄성 미끄럼 대상 을 사용 하 였 습 니 다.
구성 요소 가 FrameLayout 를 계승 하 는 이 유 는 지시 에 사용 되 는 작은 원점 이 view 위 에 나타 나 고 하나의 view 가 다른 view 위 에 중첩 되 어 있 기 때 문 입 니 다.이것 이 바로 FrameLayout 의 특성 입 니 다.
2.기능,효과
banner 속성 은 동적 으로 설정 할 수 있 습 니 다.기본 수량 은 4 이 고 기본 수량 을 조정 할 수 있 습 니 다.
banner 정 보 는 배경 에서 가 져 옵 니 다.banner 의 줄 수 는 화면의 수량 입 니 다.
자동 으로 미 끄 러 질 수도 있 고 수 동 으로 미 끄 러 질 수도 있어 요.
그림 을 다 중 스 레 드 로 다운로드 하고 흔히 볼 수 있 는 3 급 cache 정책(메모리,파일,네트워크)을 사용 하여 데 이 터 를 절약 하고 OOM 이상 을 처리 합 니 다.
내부 에서 클릭 이 벤트 를 처리 하 는 동시에 인터페이스 함 수 를 미리 남 겨 두 었 습 니 다.
banner 는 하나의 View Group 클래스 로 패키지 되 어 있 으 며,사용 하기에 간단 하 며,최소 두 줄 의 코드 만 필요 합 니 다.
3.코드
코드 주석 은 비교적 상세 하 게 쓰 여 있어 서 이해 하기 쉬 울 것 이다.두 개의 파일 로 나 뉘 는데 하 나 는 배 너의 클래스 이 고 다른 하 나 는 인터페이스 성명 이다.
ScrollBanner.java
/**
* ScrollBanner FrameLayout , , 。<br/>
* :<br/>
* ScrollBanner scrollBanner = new ScrollBanner(this, mScreenWidth, 100, this);<br/>
* linearLayout.addView(scrollBanner);<br/>
* :<br/>
*1. ScrollBanner LayoutParams, , <br/>
*2. null, <br/>
*3. setOverScrollMode banner <br/>
*4 xml banner, :<br/>
* setResolution(width, height);<br/>
setOnBannerClickListener(bannerClickListener);<br/>
showBanner()<br/>
* @author singwhatiwanna
* @version 2013.3.4
*
*/
public class ScrollBanner extends FrameLayout implements
ComponentCallBack.OnBannerClickListener,
ResponseHandler.BannerInfoHandler
{
private static final String TAG = "ScrollBanner";
private HorizontalScrollViewEx mHorizontalScrollViewEx;
//ScrollBanner view
private LinearLayout linearLayoutScrolLayout;
//linearLayoutScrolLayout view,
private LinearLayout linearLayoutForDot;
private Scroller mScroller;
private Context mContext;
private OnBannerClickListener mBannerClickListener;
// bitmap
private List<View> mLinearLayoutScreens = new ArrayList<View>();
private List<Bitmap> mBannerBitmaps = new ArrayList<Bitmap>();
//banner
private List<BannerItem> mBannerItemsList = new ArrayList<BannerItem>();
//
private List<ImageView> mImageViewList = new ArrayList<ImageView>();
private Drawable mPageIndicator;
private Drawable mPageIndicatorFocused;
//banner
private Bitmap mDefaultBitmap;
private int mScreenWidth;
private int mScreenHeight;
private int mScrollX;
//current screen index
private int mWhich = 0;
public static final int MESSAGE_AUTO_SCROLL = 1;
public static final int MESSAGE_FETCH_BANNER_SUCCESS = 2;
public static final int MARGIN_BOTTOM = 2;
//480*150 banner 150.0/480=0.3125f
public static final float ratio = 0.3125f;
//banner
private int mLocation = -1;
//banner
private int PAGE_COUNT = 4;
//
private boolean mScrollToRight = true;
//
private boolean mTimerResume = true;
//
private boolean mByUserAction = false;
// banner
private boolean mOverScrollMode = false;
// banner
private int mOverScrollDistance = 0;
// banner
final Timer timer = new Timer();
// :ms
public static final int TIMER_DURATION = 5000;
private TimerTask mTimerTask = new TimerTask()
{
@Override
public void run()
{
if (mTimerResume && !mByUserAction)
{
mHandler.sendEmptyMessage(MESSAGE_AUTO_SCROLL);
}
mByUserAction = false;
}
};
//ScrollBanner handler
private Handler mHandler = new Handler()
{
public void handleMessage(Message msg)
{
// onDetachedFromWindow,banner
if( mBannerBitmaps == null || mLinearLayoutScreens == null ||
mImageViewList == null || mBannerItemsList == null || mContext == null )
return;
switch (msg.what)
{
case MESSAGE_AUTO_SCROLL:
if (mWhich == PAGE_COUNT - 1)
mScrollToRight = false;
else if(mWhich == 0)
{
mScrollToRight = true;
}
if (mScrollToRight)
mWhich++;
else
{
mWhich--;
}
mHorizontalScrollViewEx.switchView(mWhich);
break;
case MESSAGE_FETCH_BANNER_SUCCESS:
int more = 0;
if(mBannerItemsList != null)
more = mBannerItemsList.size() - PAGE_COUNT;
if(mBannerItemsList.size() > 0)
{
// banner
ScrollBanner.this.show(true);
}
// banneritem 4
if(more > 0)
{
for (int i = 0; i < more; i++)
addBannerItem();
}
fetchBannerImages();
break;
default:
break;
}
};
};
// bitmap
private Handler mBitmapHandler = new Handler()
{
public void handleMessage(Message msg)
{
// onDetachedFromWindow,banner
if( mBannerBitmaps == null || mLinearLayoutScreens == null ||
mImageViewList == null || mBannerItemsList == null || mContext == null )
return;
Bitmap bitmap = (Bitmap)msg.obj;
String urlString = msg.getData().getString("url");
Logger.d(TAG, "url=" + urlString);
if (urlString == null || bitmap == null || mBannerItemsList == null)
{
Logger.w(TAG, "bitmap=null imgurl=" + urlString);
return;
}
for( int i = 0; i < mBannerItemsList.size(); i++ )
{
BannerItem item = mBannerItemsList.get(i);
if(item != null && urlString.equals(item.imgUrl) )
{
Logger.d(TAG, "find " + i + urlString);
if( mBannerBitmaps != null )
{
mBannerBitmaps.set( i, bitmap );
setBannerImages(i);
}
break;
}
}
};
};
public ScrollBanner(Context context)
{
this(context, null);
}
public ScrollBanner(Context context, AttributeSet attrs)
{
super(context, attrs);
mContext = context;
}
public ScrollBanner(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
mContext = context;
}
/**
*
* @param context activity
* @param width banner px
* @param height banner dip,-1
* @param bannerClickListener banner
*/
public ScrollBanner(Context context, final int width, final int height, OnBannerClickListener bannerClickListener)
{
this(context, null);
int activityId = ( (BaseActivity)context ).activityId();
if(activityId == BaseActivity.ACCOUNT_ID)// 3
mLocation = 3;
else if(activityId == BaseActivity.GAMEZONE_ID)// 2
{
mLocation = 2;
}
// banner
this.show(false);
setResolution(width, height);
setOnBannerClickListener(bannerClickListener);
setDefaultBannerImages();
fetchBannerInfo();
}
/**
* xml banner,
*/
public void showBanner()
{
int activityId = ( (BaseActivity)mContext ).activityId();
if(activityId == BaseActivity.ACCOUNT_ID)// 3
mLocation = 3;
else if(activityId == BaseActivity.GAMEZONE_ID)// 2
{
mLocation = 2;
}
setDefaultBannerImages();
fetchBannerInfo();
}
/**
*
*/
public void pauseScroll()
{
mTimerResume = false;
}
/**
*
*/
public void resumeScroll()
{
mTimerResume = true;
}
/**
*
* @param callBack banner
*/
public void setOnBannerClickListener(OnBannerClickListener bannerClickListener)
{
mBannerClickListener = (bannerClickListener != null ? bannerClickListener : ScrollBanner.this);
}
/**
* banner
* @param width banner
* @param height banner
*/
public void setResolution(final int width, final int height)
{
int heightInPx = height;
if(height == -1)
heightInPx = (int)(ratio * width) ;
else
{
Resources resources = getResources();
heightInPx = Math.round( TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, height, resources.getDisplayMetrics()) );
}
mScreenWidth = width;
mScreenHeight = heightInPx;
setLayoutParams(new LayoutParams(width, heightInPx));
initScrollView();
}
/**
* banner
* @return banner :px
*/
public int getHeightPixels()
{
return mScreenHeight;
}
/**
* banner
* @param canOverScroll true ,false
*/
public void setOverScrollMode(boolean canOverScroll)
{
mOverScrollMode = canOverScroll;
if(canOverScroll == false)
mOverScrollDistance = 0;
}
/**
* banner
*/
private void fetchBannerInfo()
{
NetworkManager netManager = (NetworkManager) AppEngine.getInstance().getManager(
IManager.NETWORK_ID);
netManager.getBannerInfo( String.valueOf(mLocation), ScrollBanner.this );
}
/**
* banner
*/
private void setDefaultBannerImages()
{
// banner bitmap
BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();
bitmapFactoryOptions.inJustDecodeBounds = false;
bitmapFactoryOptions.inSampleSize = 2;
Resources res=mContext.getResources();
mDefaultBitmap = BitmapFactory.decodeResource(res, R.drawable.banner_image_default, bitmapFactoryOptions);
for(int i = 0; i < PAGE_COUNT; i++)
mBannerBitmaps.add(i, mDefaultBitmap);
// BannerItem
for (int i = 0; i < PAGE_COUNT; i++)
mBannerItemsList.add(i, null);
setBannerImages(-1);
}
private void fetchBannerImages()
{
// onDetachedFromWindow,banner
if( mBannerItemsList == null )
return;
//ImageManager url bitmap
ImageManager imageManager = (ImageManager)AppEngine.getInstance().
getManager(IManager.IMAGE_ID);
BannerItem item = null;
for(int i = 0; i < PAGE_COUNT; i++)
{
try
{
item = mBannerItemsList.get(i);
}
catch (IndexOutOfBoundsException e)
{
Logger.e(TAG, "fetchBannerImages error: " + e);
}
catch (Exception e)
{
Logger.e(TAG, "fetchBannerImages error: " + e);
}
//ImageManager , cache ( 、 、 )
if( item != null && item.imgUrl != null )
imageManager.loadBitmap( item.imgUrl, mBitmapHandler );
}
}
/**
* banner
* @param position position=-1, bitmap
*/
private void setBannerImages(final int position)
{
int size = mBannerBitmaps.size();
if (size < PAGE_COUNT || mLinearLayoutScreens == null)
{
return;
}
if(position >=0 && position < PAGE_COUNT )
{
Drawable drawable = mLinearLayoutScreens.get(position).getBackground();
mLinearLayoutScreens.get(position).setBackgroundDrawable
(new BitmapDrawable( mBannerBitmaps.get(position) ) );
drawable.setCallback(null);
drawable = null;
return;
}
for(int i = 0; i < PAGE_COUNT; i++)
{
mLinearLayoutScreens.get(i).setBackgroundDrawable(new BitmapDrawable(mBannerBitmaps.get(i)));
}
}
/**
* banner
* @param isShow true false
*/
public void show(boolean isShow)
{
if(isShow)
{
this.setVisibility(View.VISIBLE);
mTimerResume = true;
}
else
{
this.setVisibility(View.GONE);
mTimerResume = false;
}
}
/**
*
* @param which
*/
public void switchToScreen(final int which)
{
mHorizontalScrollViewEx.switchView(which);
}
/**
* ( )
* @param count
*/
protected void setScreenCount(final int count)
{
PAGE_COUNT = count;
}
/**
* mOverScrollMode false, ( )
* @param distance
*/
protected void setOverScrollDistance(int distance)
{
if(distance < 0)
distance = 0;
mOverScrollDistance = mOverScrollMode ? distance : 0;
}
/**
*
* @param position current screen index
*/
private void switchScreenPosition(final int position)
{
if( mPageIndicator == null || mPageIndicatorFocused == null )
return;
int length = 0;
if(mImageViewList != null)
length = mImageViewList.size();
if (position >= length || position < 0 || length <= 0)
{
return;
}
for(int i = 0; i < length; i++)
{
mImageViewList.get(i).setImageDrawable(mPageIndicator);
}
mImageViewList.get(position).setImageDrawable(mPageIndicatorFocused);
}
/**
* FrameLayout
*/
private void initScrollView()
{
setLayoutParams(new LayoutParams(mScreenWidth, mScreenHeight ));
linearLayoutScrolLayout = new LinearLayout(mContext);
linearLayoutScrolLayout.setBackgroundColor(Color.WHITE);
linearLayoutScrolLayout.setOrientation(LinearLayout.HORIZONTAL);
int mVersionCode = 8;
try
{
mVersionCode = Integer.valueOf(android.os.Build.VERSION.SDK);
Logger.d(TAG, "sdk version=" + mVersionCode);
}
catch (Exception e)
{
e.printStackTrace();
}
// android1.6 android bug
if(mVersionCode <= 5)
{
linearLayoutScrolLayout.setBaselineAligned(false);
}
// view
for(int i = 0; i < PAGE_COUNT; i++)
{
LinearLayout linearLayoutScreen = new LinearLayout(mContext);
linearLayoutScreen.setOrientation(LinearLayout.VERTICAL);
linearLayoutScrolLayout.addView(linearLayoutScreen, new LayoutParams(
mScreenWidth,
LayoutParams.FILL_PARENT));
mLinearLayoutScreens.add(i, linearLayoutScreen);
}
//
RelativeLayout relativeLayout = new RelativeLayout(mContext);
relativeLayout.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
//linearLayoutForDot
linearLayoutForDot =new LinearLayout(mContext);
android.widget.RelativeLayout.LayoutParams layoutParams =
new android.widget.RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
// :px
layoutParams.bottomMargin = MARGIN_BOTTOM;
layoutParams.rightMargin = MARGIN_BOTTOM;
layoutParams.addRule(android.widget.RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutParams.addRule(android.widget.RelativeLayout.CENTER_HORIZONTAL);
linearLayoutForDot.setLayoutParams(layoutParams);
linearLayoutForDot.setOrientation(LinearLayout.HORIZONTAL);
linearLayoutForDot.setHorizontalGravity(Gravity.CENTER);
linearLayoutForDot.setVerticalGravity(Gravity.CENTER);
//
// linearLayoutForDot.setBackgroundResource(R.drawable.round_corner_bg);
// linearLayoutForDot.getBackground().setAlpha(100);
// 4
mPageIndicator = getResources().getDrawable(R.drawable.page_indicator);
mPageIndicatorFocused = getResources().getDrawable(R.drawable.page_indicator_focused);
for(int i = 0; i < PAGE_COUNT; i++)
{
ImageView imageView = new ImageView(mContext);
imageView.setImageDrawable(mPageIndicator);
mImageViewList.add(i, imageView);
LinearLayout.LayoutParams layoutParamsForDot =
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layoutParamsForDot.rightMargin = 5;
linearLayoutForDot.addView(imageView, layoutParamsForDot);
}
mImageViewList.get(0).setImageDrawable(mPageIndicatorFocused);
relativeLayout.addView(linearLayoutForDot);
mHorizontalScrollViewEx = new HorizontalScrollViewEx(mContext, null, mBannerClickListener);
mHorizontalScrollViewEx.setLayoutParams(new LayoutParams(
mScreenWidth * PAGE_COUNT,
LayoutParams.FILL_PARENT));
mHorizontalScrollViewEx.addView(linearLayoutScrolLayout, new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
mHorizontalScrollViewEx.setHorizontalScrollBarEnabled(false);
mHorizontalScrollViewEx.setHorizontalFadingEdgeEnabled(false);
addView(mHorizontalScrollViewEx);
addView(relativeLayout);
// 5
timer.schedule(mTimerTask, 5000, TIMER_DURATION);
}
/**
* banner TODO
*/
private void addBannerItem()
{
// onDetachedFromWindow,banner
if( mBannerBitmaps == null || mLinearLayoutScreens == null ||
mImageViewList == null || mContext == null )
return;
//
PAGE_COUNT += 1;
mHorizontalScrollViewEx.getLayoutParams().width = mScreenWidth * PAGE_COUNT;
//
if(mDefaultBitmap == null)
{
BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();
bitmapFactoryOptions.inJustDecodeBounds = false;
bitmapFactoryOptions.inSampleSize = 2;
Resources res=mContext.getResources();
mDefaultBitmap = BitmapFactory.decodeResource(res, R.drawable.banner_image_default, bitmapFactoryOptions);
}
mBannerBitmaps.add(mDefaultBitmap);
mBannerItemsList.add(null);
//
LinearLayout linearLayoutScreen = new LinearLayout(mContext);
linearLayoutScreen.setOrientation(LinearLayout.VERTICAL);
linearLayoutScreen.setBackgroundDrawable(new BitmapDrawable( mBannerBitmaps.get(PAGE_COUNT - 1) ));
linearLayoutScrolLayout.addView(linearLayoutScreen, new LayoutParams(
mScreenWidth,
LayoutParams.FILL_PARENT));
mLinearLayoutScreens.add(linearLayoutScreen);
//
ImageView imageView = new ImageView(mContext);
imageView.setImageDrawable(mPageIndicator);
mImageViewList.add(imageView);
LinearLayout.LayoutParams layoutParamsForDot =
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layoutParamsForDot.rightMargin = 5;
linearLayoutForDot.addView(imageView, layoutParamsForDot);
}
private class HorizontalScrollViewEx extends ViewGroup implements
OnGestureListener
{
private GestureDetector mGestureDetector;
private int mWhichScreen;
public HorizontalScrollViewEx(Context context, AttributeSet attrs, OnBannerClickListener bannerClickListener)
{
super(context, attrs);
mGestureDetector = new GestureDetector(this);
//
mGestureDetector.setIsLongpressEnabled(false);
//
mScroller = new Scroller(context);
}
/**
*
* @param whichScreen index
*/
public void switchView(int whichScreen)
{
if(mLinearLayoutScreens == null)
return;
//
if (whichScreen < 0)
whichScreen = 0;
else if(whichScreen >= PAGE_COUNT)
whichScreen = PAGE_COUNT - 1;
Logger.i(TAG, "switch view to " + whichScreen);
int delta = whichScreen * mScreenWidth - HorizontalScrollViewEx.this.getScrollX();
//
mScroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta) * 3);
// refresh
invalidate();
//delta>0 stands for user scroll view to right
if (delta > 0)
mScrollToRight = true;
else
{
mScrollToRight = false;
}
mWhichScreen = whichScreen;
mWhich = whichScreen;
//
switchScreenPosition(mWhichScreen);
}
/**
* , 1 MotionEvent ACTION_DOWN
*/
@Override
public boolean onDown(MotionEvent e)
{
Logger.i("MyGesture", "onDown");
mScrollX = HorizontalScrollViewEx.this.getScrollX();
return true;
}
/**
* , , 1 MotionEvent ACTION_DOWN
* onDown() ,
*/
public void onShowPress(MotionEvent e)
{
Logger.i("MyGesture", "onShowPress");
}
/**
* ( ) , 1 MotionEvent ACTION_UP
*/
public boolean onSingleTapUp(MotionEvent e)
{
Logger.i("MyGesture", "onSingleTapUp");
if(mBannerItemsList == null || mBannerItemsList.size() <= mWhichScreen)
return false;
BannerItem bannerItem = mBannerItemsList.get(mWhichScreen);
if(bannerItem != null)
{
BannerMotionEvent bannerMotionEvent =
new BannerMotionEvent(mWhichScreen, bannerItem.action, bannerItem.url,
bannerItem.gameId, bannerItem.gameType, bannerItem.title);
mBannerClickListener.onBannerClick(bannerMotionEvent);
}
return false;
}
/** 、 , 1 MotionEvent ACTION_DOWN, ACTION_MOVE,
* 1 ACTION_UP
*/
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY)
{
Logger.i("MyGesture", "onFling velocityX=" + velocityX);
mWhichScreen = velocityX > 0 ?
mWhichScreen - 1
: mWhichScreen + 1;
switchView(mWhichScreen);
return true;
}
/**
* , , 1 MotionEvent ACTION_DOWN, ACTION_MOVE
*/
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY)
{
Logger.i("MyGesture", "onScroll");
//
if (mOverScrollMode == false)
{
float x1 = e1.getX();
float x2 = e2.getX();
if(mWhichScreen == 0 && x1 < x2)
return false;
else if(mWhichScreen == PAGE_COUNT - 1 && x1 > x2)
return false;
}
// int distance = Math.abs(getScrollX() - mWhichScreen * mScreenWidth);
// if ((mWhichScreen ==0 || mWhichScreen == PAGE_COUNT -1) && distance > mOverScrollDistance)
// return false;
this.scrollBy((int)distanceX, 0);
return true;
}
/**
* , MotionEvent ACTION_DOWN
*/
public void onLongPress(MotionEvent e)
{
Logger.i("MyGesture", "onLongPress");
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
mTimerResume = false;
if ( !mScroller.isFinished() )
mScroller.abortAnimation();
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//
mTimerResume = true;
mByUserAction = true;
}
boolean consume = mGestureDetector.onTouchEvent(event);
if (consume == false && event.getAction() == MotionEvent.ACTION_UP)
{
int curScrollX = HorizontalScrollViewEx.this.getScrollX();
int mWhichScreen = (curScrollX + mScreenWidth / 2) /mScreenWidth;
switchView(mWhichScreen);
}
return consume;
}
@Override
public void computeScroll()
{
if (mScroller.computeScrollOffset())
{
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
postInvalidate();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
if (changed)
{
int childLeft = 0;
final int childCount = getChildCount();
for (int i=0; i<childCount; i++)
{
final View childView = getChildAt(i);
if (childView.getVisibility() != View.GONE)
{
final int childWidth = childView.getMeasuredWidth();
childView.layout(childLeft, 0,
childLeft+childWidth, childView.getMeasuredHeight());
childLeft += childWidth;
}
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int width = MeasureSpec.getSize(widthMeasureSpec);
final int count = getChildCount();
for (int i = 0; i < count; i++)
{
getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
}
scrollTo(mWhich * mScreenWidth, 0);
}
}
/**
* override , <br/>
* : ,
*/
@Override
public void setLayoutParams(android.view.ViewGroup.LayoutParams params)
{
params.width = mScreenWidth;
params.height = mScreenHeight;
super.setLayoutParams(params);
}
// view AttachedToWindow
@Override
protected void onAttachedToWindow()
{
super.onAttachedToWindow();
mTimerResume = true;
}
// view window, view , timer
@Override
protected void onDetachedFromWindow()
{
super.onDetachedFromWindow();
Logger.d(TAG, "onDetachedFromWindow");
mTimerResume = false;
int activityId = ( (BaseActivity)mContext ).activityId();
//
if(activityId == BaseActivity.ACCOUNT_ID)
{
destroy();
}
}
/**
* banner
*/
public void destroy()
{
mTimerTask.cancel();
timer.cancel();
// bitmap activity
destoryBitmaps();
System.gc();
}
/**
* bitmap activity
*/
private void destoryBitmaps()
{
for (View view : mLinearLayoutScreens)
{
Drawable drawable = view.getBackground();
BitmapDrawable bitmapDrawable = null;
if(drawable instanceof BitmapDrawable)
bitmapDrawable = (BitmapDrawable)drawable;
if(bitmapDrawable != null)
{
// drawable view
bitmapDrawable.setCallback(null);
bitmapDrawable = null;
}
}
for (ImageView imageView : mImageViewList)
{
Drawable drawable = imageView.getDrawable();
if(drawable != null)
{
drawable.setCallback(null);
drawable = null;
}
}
mPageIndicator.setCallback(null);
mPageIndicator = null;
mPageIndicatorFocused.setCallback(null);
mPageIndicatorFocused = null;
mLinearLayoutScreens.clear();
mLinearLayoutScreens = null;
mBannerBitmaps.clear();
mBannerBitmaps = null;
mImageViewList.clear();
mImageViewList = null;
mBannerItemsList.clear();
mBannerItemsList = null;
}
//
@Override
public void onBannerClick( BannerMotionEvent bannerMotionEvent )
{
final int position = bannerMotionEvent.index;
if(mContext == null)
return;
NotificationInfo notificationInfo = new NotificationInfo();
notificationInfo.msgType = bannerMotionEvent.getAction();
int action = bannerMotionEvent.getAction();
if(action == NotificationInfo.NOTIFICATION_SINGLEGAME_MSG) // ,
{
try
{
notificationInfo.gameId = Integer.parseInt( bannerMotionEvent.getGameId() );
notificationInfo.gameType = Integer.parseInt( bannerMotionEvent.getGameType() );
}
catch (NumberFormatException e)
{
Logger.e(TAG, e.toString());
return;
}
}
else if(action == NotificationInfo.NOTIFICATION_GAMEPAGE_MSG) // ,
{
try
{
notificationInfo.gameId = Integer.parseInt( bannerMotionEvent.getGameId() );
}
catch (NumberFormatException e)
{
Logger.e(TAG, e.toString());
return;
}
notificationInfo.issueTitle = bannerMotionEvent.getTitle();
}
else if(action == NotificationInfo.NOTIFICATION_SHOW_WEBVIEW_MSG) // , webview
{
notificationInfo.issueTitle = bannerMotionEvent.getTitle();
notificationInfo.openUrl = bannerMotionEvent.getResponseUrl();
}
else //reserved
{
return;
}
Intent intent = notificationInfo.generateIntent(mContext);
if(intent != null)
mContext.startActivity(intent);
}
/**
* ScrollBanner banner
*/
public static class BannerItem extends Object
{
public static final String ACTION = "action";
public static final String URL = "url";
public static final String IMGURL = "imgurl";
public static final String GAMEID = "gameid";
public static final String GAMETYPE = "gametype";
public static final String TITLE = "title";
public int index = -1;
public int action = -1;
public String url = "";
public String imgUrl = "";
public String gameId = "";
public String gameType = "";
public String title = "";
public BannerItem(){}
}
/**
* BannerMotionEvent: banner <br/>
*getAction() <br/>
*getResponseUrl() url<br/>
*...
*/
public static class BannerMotionEvent extends Object
{
/**
* ACTION_PLAY_FLASH:
*/
public static final int ACTION_PLAY = 2;
/**
* ACTION_HOMEPAGE:
*/
public static final int ACTION_HOMEPAGE = 3;
/**
* ACTION_OPEN_URL: url
*/
public static final int ACTION_OPEN_URL = 4;
//banner index
private int index = -1;
// url
private String responseUrl = "";
//
private int action = -1;
//gameid
private String gameId = "";
//gametype flash (0) or h5 (1)
private String gameType = "";
//webview
private String title = "";
public BannerMotionEvent(int index, int action, String responseUrl,
String gameId, String gameType, String title)
{
BannerMotionEvent.this.index = index;
BannerMotionEvent.this.action = action;
BannerMotionEvent.this.responseUrl = responseUrl;
BannerMotionEvent.this.gameId = gameId;
BannerMotionEvent.this.gameType = gameType;
BannerMotionEvent.this.title = title;
}
/**
* BannerMotionEvent
* @return :ACTION_PLAY
*/
public int getAction()
{
return action;
}
/**
* BannerMotionEvent title
* @return title webview
*/
public String getTitle()
{
return title;
}
/**
* BannerMotionEvent gameId
* @return gameId
*/
public String getGameId()
{
return gameId;
}
/**
* BannerMotionEvent gameType
* @return gameType 0 or 1
*/
public String getGameType()
{
return gameType;
}
/**
* BannerMotionEvent url
* @return url
*/
public String getResponseUrl()
{
return responseUrl;
}
@SuppressLint("DefaultLocale")
@Override
public String toString()
{
return String.format("BannerMotionEvent { index=%d, action=%d, responseUrl=%s, gameId=%s, gameType=%s, title=%s }",
index, action, responseUrl, gameId, gameType, title);
}
}
@Override
public void onBannerInfoSuccess(List<BannerItem> items)
{
Logger.d(TAG, "onBannerInfoSuccess");
mBannerItemsList = items;
mHandler.sendEmptyMessage(MESSAGE_FETCH_BANNER_SUCCESS);
}
@Override
public void onBannerInfoFailed()
{
Logger.e(TAG, "onBannerInfoFailed");
}
}
ComponentCallBack.java
public interface ComponentCallBack
{
public static interface OnBannerClickListener
{
/**
* banner
* @param bannerMotionEvent ,
* {@link BannerMotionEvent}
*/
public abstract void onBannerClick( BannerMotionEvent bannerMotionEvent );
}
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.