I am getting null pointer on back press of activity where I have used the custom view. Where am I doing wrong?? Below is my custom view class:
public class PuzzleBoardView extends View implements ViewTreeObserver.OnGlobalLayoutListener {
public static final int NUM_SHUFFLE_STEPS = 40;
Comparator<PuzzleBoard> comparator = new PuzzleBoardComparator();
PriorityQueue<PuzzleBoard> queue = new PriorityQueue<>(9999, comparator);
private PuzzleActivity activity;
private PuzzleBoard puzzleBoard;
private ArrayList<PuzzleBoard> animation;
private Random random = new Random();
private Bitmap imgBitmap;
public PuzzleBoardView(Context context) {
super(context);
setMinimumWidth(50);
activity = (PuzzleActivity) context;
animation = null;
}
public void initialize(final Bitmap imageBitmap, Activity parent) {
final int width = getWidth();
imgBitmap = imageBitmap;
Log.d("PuzzleBoardView", "initialize: width=== " + width);
addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View v) {
Log.d("PuzzleBoardView", "onViewAttachedToWindow=== " + width);
puzzleBoard = new PuzzleBoard(imgBitmap, getWidth());
shuffle();
}
#Override
public void onViewDetachedFromWindow(View v) {
Log.d("PuzzleBoardView", "onViewDetachedFromWindow=== ");
onDetachedFromWindow();
}
});
}
public void clearView() {
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d("TAG", "onDraw: =====");
if (puzzleBoard != null) {
Log.d("TAG", "onDraw:111 =====");
if (animation != null && animation.size() > 0) {
puzzleBoard = animation.remove(0);
puzzleBoard.draw(canvas);
if (animation.size() == 0) {
animation = null;
puzzleBoard.reset();
Toast toast = Toast.makeText(activity, "Solved! ", Toast.LENGTH_LONG);
toast.show();
} else {
this.postInvalidateDelayed(500);
}
} else {
puzzleBoard.draw(canvas);
}
}
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
getViewTreeObserver().addOnGlobalLayoutListener(this);
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
Log.d("PuzzleBoardView", "onDetachedFromWindow=== ");
getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
public void shuffle() {
if (animation == null && puzzleBoard != null) {
// Do something. Then:
ArrayList<PuzzleBoard> boards;
for (int i = 0; i <= NUM_SHUFFLE_STEPS; i++) {
boards = puzzleBoard.neighbours();
puzzleBoard = boards.get(random.nextInt(boards.size()));
}
puzzleBoard.reset();
invalidate();
queue.clear();
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (animation == null && puzzleBoard != null) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (puzzleBoard.click(event.getX(), event.getY())) {
invalidate();
if (puzzleBoard.resolved()) {
/*Toast toast = Toast.makeText(activity, "Congratulations!", Toast.LENGTH_LONG);
toast.show();*/
activity.puzzleSolved();
}
return true;
}
}
}
return super.onTouchEvent(event);
}
public void solve() {
puzzleBoard.steps = 0;
puzzleBoard.previousBoard = null;
queue.add(puzzleBoard);
PuzzleBoard prev = null;
ArrayList<PuzzleBoard> solution = new ArrayList<>();
while (!queue.isEmpty()) {
PuzzleBoard lowest = queue.poll();
if (lowest.priority() - lowest.steps != 0) {
for (PuzzleBoard toAdd : lowest.neighbours()) {
if (!toAdd.equals(prev)) {
queue.add(toAdd);
}
}
prev = lowest;
} else {
solution.add(lowest);
while (lowest != null) {
if (lowest.getPreviousBoard() == null) {
break;
}
solution.add(lowest.getPreviousBoard());
lowest = lowest.getPreviousBoard();
}
Collections.reverse(solution);
animation = solution;
invalidate();
break;
}
}
}
public PuzzleBoard getPuzzleBoard() {
return puzzleBoard;
}
public void setPuzzleBoard(PuzzleBoard puzzleBoard) {
this.puzzleBoard = puzzleBoard;
}
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
Log.d("PuzzleBoardView", "onAttachedToWindow: width=== " + getWidth());
puzzleBoard = new PuzzleBoard(imgBitmap, getWidth());
shuffle();
}
}
class PuzzleBoardComparator implements Comparator<PuzzleBoard> {
#Override
public int compare(PuzzleBoard first, PuzzleBoard second) {
if (first.priority() == second.priority()) {
return 0;
} else if (first.priority() < second.priority()) {
return -1;
} else {
return 1;
}
}
}
Here is my Exception
java.lang.NullPointerException: Attempt to invoke interface method 'void android.view.View$OnAttachStateChangeListener.onViewDetachedFromWindow(android.view.View)' on a null object reference
Change your code like below.
public PuzzleBoardView(Context context) {
super(context);
setMinimumWidth(50);
activity = (PuzzleActivity) context;
animation = null;
if(activity!=null)
initialize();
}
and remove initialize method from onCreate()
I wrote a little STT-functionality, with a floating button that is pulsating after being clicked on to notify that the app is listening. This works quite well so far with the one annoying behavior that my floating button does not return to its original size in some cases.
The animation increases and decreases the size of the button, and I guess it gets stuck in the increased state, hence the randomness of this behavior. I just can't figure out how to catch that and set the size to the original one.
Action Listener of my Button:
private View.OnTouchListener setVoiceButtonOnClick()
{
return new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
if(!voiceButton.isInitialized())
voiceButton.initAnimationValues();
voiceButton.setPressed(true);
listen();
}
return true;
}
};
}
My Button extends FloatingActionButton, and does the following:
public class FloatingVoiceButton extends FloatingActionButton
{
public static final float DEFAULT_ANIMATION_FACTOR = 1.2f;
private boolean isInitialized = false;
private int originalHeight;
private int originalWidth;
private boolean isAnimationRunning;
private ObjectAnimator animator;
public FloatingVoiceButton(Context context)
{
super(context);
}
public void initAnimationValues()
{
isInitialized = true;
isAnimationRunning = false;
originalHeight = getMeasuredHeight();
originalWidth = getMeasuredWidth();
animator = ObjectAnimator.ofPropertyValuesHolder(
this,
PropertyValuesHolder.ofFloat("scaleX", DEFAULT_ANIMATION_FACTOR),
PropertyValuesHolder.ofFloat("scaleY", DEFAULT_ANIMATION_FACTOR));
animator.setDuration(200);
animator.setRepeatCount(ObjectAnimator.INFINITE);
animator.setRepeatMode(ObjectAnimator.REVERSE);
}
public boolean isInitialized()
{
return isInitialized;
}
public void resetButtonSize()
{
setMeasuredDimension(originalWidth, originalHeight);
}
public boolean isAnimationRunning()
{
return isAnimationRunning;
}
public void animate(boolean doAnimation)
{
isAnimationRunning = doAnimation;
if(doAnimation)
animator.start();
else
{
animator.end();
setPressed(false);
resetButtonSize();
//destroyDrawingCache(); tried these without success
//postInvalidate();
}
}
}
Finally I am controlling the button the start and end of the animation with my RecognitionListener:
public class InputVoiceRecognitionListener implements RecognitionListener
{
private EditText targetEditText;
private String originalContent;
private final String DELIMITER = "\n\n";
private FloatingVoiceButton button;
public InputVoiceRecognitionListener(EditText editText, FloatingVoiceButton button)
{
targetEditText = editText;
originalContent = editText.getText().toString();
this.button = button;
}
#Override
public void onReadyForSpeech(Bundle params)
{
button.animate(true);
}
#Override
public void onBeginningOfSpeech()
{
originalContent = targetEditText.getText().toString();
}
#Override
public void onRmsChanged(float rmsdB)
{}
#Override
public void onBufferReceived(byte[] buffer)
{}
#Override
public void onEndOfSpeech()
{
if(button.isAnimationRunning())
button.animate(false);
}
#Override
public void onError(int error)
{
if(button.isAnimationRunning())
button.animate(false);
}
#Override
public void onResults(Bundle results)
{
setRecognizedText(results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION));
}
#Override
public void onPartialResults(Bundle partialResults)
{
setRecognizedText(partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION));
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
private void setRecognizedText(ArrayList<String> matches)
{
String result = "";
if(matches != null)
result = matches.get(0);
if((originalContent.trim()).length() > 0)
{
if(!originalContent.endsWith("\n\n"))
result = originalContent + DELIMITER + result;
else result = originalContent + result;
}
targetEditText.setText(result);
targetEditText.setSelection(result.length());
}
}
EDIT
This did it for me:
resettingAnimator = ObjectAnimator.ofPropertyValuesHolder(
this,
PropertyValuesHolder.ofFloat("scaleX", 1.0f),
PropertyValuesHolder.ofFloat("scaleY", 1.0f));
resettingAnimator.setDuration(0);
resettingAnimator.setRepeatCount(1);
and calling resettingAnimator.start(); when I finish my main animation.
Simple solution to this problem is that you define another animation after stopping your repeating one.
I just can't figure out how to catch that and set the size to the original one.
You, that is View, does know what is the "original" size, its the size of the scale factor 1f. So after stopping repeating animation just make another animations to set scale to 1f
PropertyValuesHolder.ofFloat("scaleX", 1f)
PropertyValuesHolder.ofFloat("scaleY", 1f))
This animation will run always, but will not be visible if your button is already at "normal" size.
With this in mind I would recommend that you use some other flag than isAnimationRunning(), either by some state (ex. selected) of your Fab, or some manually set arbitrary boolean.
I have an activity like below. I want the threads inside the activity terminate when the activity is paused or stopped. I searched and found volatile Boolean solution which didn't work for me. When i put the activity in pause or stop state, download continues, which i don't want it.
public class MyActivity extends Activity {
//some code here
private void foo(){
new Thread (new Runnable (){
#Override
public void run() {
//download something from internet
}
}).start();
}
}
i used this pattern which didn't work:
public class MyActivity extends Activity {
volatile Boolean state = true;
//some code here
private void foo(){
new Thread (new Runnable (){
#Override
public void run() {
while (state) {
//download something from internet
}
}
}).start();
}
#Override
public void onPause(){
super.onPause();
state = false;
}
#Override
public void onStop(){
super.onStop();
state = false;
}
}
Here's an example of the structure of a thread which stops when back is hit, which I made for my game (and works). One key difference is you're using a thread in your Activity, while in mine I call a View in my Activity and run the thread in the View. If I hit back, I return to my Activity, and can call the thread again by hitting 'start.' BECAUSE my thread behaves the way you want yours too, even if it's happening in View, I thought you may find it helpful.
Where my of my synchronization happens is with the touchscreen values, and making sure those are updated in the thread and calling function.
The thread is trashed totally unless you have a way of saving the state (if you need to).
Your thread will need to synchronize with other functions you want controlling/sharing values with the thread, like onPause, etc..
**you'll need to have some synchronized test value inside your while loop which can then change state to false, otherwise the thread will continue on its own, which is the point of threads.
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
private final GameActivity gameActivity;
private GameThread _thread;
private boolean previouslyRunning = false;
private int width; //Screen width
private int height; //Screen height
private boolean newGame = true;
public GameView(Context context) {
super(context);
getHolder().addCallback(this);
this.gameActivity = (GameActivity) context;
_thread = new GameThread(getHolder(), this);
setFocusable(true);
setFocusableInTouchMode(true);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
width = w;
height = h;
super.onSizeChanged(w, h, oldw, oldh);
//_thread.initialize();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (!previouslyRunning) {
_thread = new GameThread(getHolder(), this);
_thread.initialize();
}
_thread.setRunning(true);
_thread.start();
previouslyRunning = true;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
//TODO - this was an Auto-generated method stub...
//TODO - research what this might be useful for
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
//Put stuff that needs destructed here.
boolean retry = true;
_thread.setRunning(false);
while (retry) {
try {
_thread.join();
retry = false;
} catch (InterruptedException e) {
// will will try again and again
//TODO: figure it out....
}
}
}
public boolean onTouchEvent(MotionEvent event) {
int numPointers = event.getPointerCount();
int ptrIdx = 0;
int touch = event.getActionMasked();
if (touch == MotionEvent.ACTION_DOWN) {
while (ptrIdx < numPointers) {
int id = event.getPointerId(ptrIdx);
float xp = event.getX(ptrIdx) / width;
if (xp > 0.6) {
_thread.shieldFront = false;
}
if (xp > 0.6 && !attacks) {
attacks = true;
_thread.attackandDefendToggle(true);
} else if (xp > 0.6 && attacks) {
attacks = false;
_thread.attackandDefendToggle(false);
} else if ((xp < 0.4 && xp > 0.2) && !movedRight) {
movedRight = true;
_thread.moveRight(true);
} else if ((xp < 0.4 && xp > 0.2) && movedRight) {
movedRight = false;
_thread.moveRight(false);
} else if (xp < 0.2 && !movedLeft) {
movedLeft = true;
_thread.moveLeft(true);
} else if (xp < 0.2 && movedLeft) {
movedLeft = false;
_thread.moveLeft(false);
}
ptrIdx++;
}
}
if (touch == MotionEvent.ACTION_UP) {
_thread.moveLeft(false);
_thread.moveRight(false);
_thread.attackandDefendToggle(false);
attacks = false;
_thread.shieldFront = true;
}
return true;
}
class GameThread extends Thread {
/****************************
* Public functions *
****************************/
public GameThread(SurfaceHolder surfaceHolder, GameView panel) {
_surfaceHolder = surfaceHolder;
_panel = panel;
// put sounds here.
soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
//more sounds later
//TODO: create sounds
}
/************************************************
* update() function updates all variables, *
* such as physics, Canvas draw points, score *
* life, etc.. It is called before draw. *
************************************************/
private void update() {
// all the values I want updated with each callback
}
/************************************************
* draw() function creates images on screen, *
* but it performs no logic. *
************************************************/
private void draw(Canvas canvas) {
if (canvas == null) {
return;
}
//Draw stuff on screen
}
public void initialize() {
// Values I want the program to start with;
}
public void setRunning(boolean run) {
_run = run;
}
//Code below actually runs the thread.
#Override
public void run() {
Canvas c;
while (_run) {
c = null;
try {
c = _surfaceHolder.lockCanvas(null);
synchronized (_surfaceHolder) {
// Update the game state
update();
// Draw image
draw(c);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
I have a background animation drawn onto a SurfaceView by another thread in my app. The animation seems to work well except when the screen is rotated. Then the main thread will sometimes hang for a couple of seconds. Using DDMS I see that the main thread is calling Object.wait(), I don't understand where or why it's doing that though.
Below is some abbreviated code, if needed the full source can be found on github at https://github.com/GavinDBrown/Amazing.
Main Activity:
public class StartMenu extends Activity {
/** A handle to the thread that's running the Game Of Life animation. */
private GOLThread mGOLThread;
/** A handle to the View in which the background is running. */
private GOLView mGOLView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_of_life_background);
startGOLBackground();
}
private void startGOLBackground() {
// get handles to the GOLView and it's GOLThread
mGOLView = (GOLView) findViewById(R.id.game_of_life_background);
mGOLThread = new GOLThread(mGOLView.getHolder());
mGOLView.setThread(mGOLThread);
mGOLThread.start();
}
private void stopGOLBackground() {
if (mGOLThread != null) {
mGOLThread.halt(); // stop the animation if it's valid
boolean retry = true;
while (retry) {
try {
mGOLThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
mGOLThread = null;
mGOLView = null;
}
}
#Override
public void onResume() {
super.onResume();
mGOLThread = mGOLView.getThread();
mGOLThread.unpause();
}
#Override
public void onPause() {
super.onPause();
mGOLThread.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
stopGOLBackground();
}
}
The SurfaceView:
public class GOLView extends SurfaceView implements SurfaceHolder.Callback {
/** The thread that actually draws the animation */
private GOLThread thread;
SurfaceHolder surfaceHolder;
public GOLView(Context context, AttributeSet attrs) {
super(context, attrs);
SurfaceHolder holder = getHolder();
holder.addCallback(this);
}
#Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
if (hasWindowFocus){
thread.unpause();
} else {
thread.pause();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
thread.setSurfaceSize(width, height);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
thread.pause();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
thread.unpause();
}
}
And finally the Thread:
public class GOLThread extends Thread {
private GameOfLife gameOfLife;
private final Object GOLLock = new Object();
private int mCanvasHeight;
private int mCanvasWidth;
private SurfaceHolder mSurfaceHolder;
public GOLThread(SurfaceHolder surfaceHolder) {
mSurfaceHolder = surfaceHolder;
}
#Override
public void start() {
synchronized (mSurfaceHolder) {
stopped = false;
mSurfaceHolder.notify();
}
super.start();
}
public void halt() {
synchronized (mSurfaceHolder) {
paused = true;
stopped = true;
mSurfaceHolder.notify();
}
}
public void pause() {
synchronized (mSurfaceHolder) {
paused = true;
}
}
public void unpause() {
synchronized (mSurfaceHolder) {
paused = false;
mSurfaceHolder.notify();
}
}
public Bundle saveState(Bundle outState) {
synchronized (GOLLock) {
if (outState != null) {
outState.putParcelable(GAME_OF_LIFE_ID, gameOfLife);
}
}
return outState;
}
public synchronized void restoreState(Bundle savedState) {
synchronized (GOLLock) {
gameOfLife = (GameOfLife) savedState.getParcelable(GAME_OF_LIFE_ID);
}
}
#Override
public void run() {
while (!stopped) {
while (paused && !stopped) {
try {
synchronized (mSurfaceHolder) {
mSurfaceHolder.wait(100L);
}
} catch (InterruptedException ignore) {
}
}
// Check if thread was stopped while it was paused.
if (stopped)
break;
beforeTime = System.nanoTime();
Canvas c = null;
try {
c = mSurfaceHolder.lockCanvas();
synchronized (GOLLock) {
if (gameOfLife != null) {
gameOfLife.drawAndUpdate(c);
} else {
pause();
}
}
} finally {
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
sleepTime = FRAME_DELAY
- ((System.nanoTime() - beforeTime) / 1000000L);
try {
// actual sleep code
if (sleepTime > 0 && !stopped && !paused) {
synchronized (mSurfaceHolder) {
mSurfaceHolder.wait(sleepTime);
}
}
} catch (InterruptedException ex) {
}
}
}
public void setSurfaceSize(int width, int height) {
synchronized (GOLLock) {
if (mCanvasWidth != width || mCanvasHeight != height) {
mCanvasWidth = width;
mCanvasHeight = height;
// reset the GOL
if (mCanvasWidth > 0 && mCanvasHeight > 0) {
gameOfLife = new GameOfLife();
gameOfLife.init(mCanvasWidth, mCanvasHeight);
}
}
}
}
}
The problem is GOLThread is calling SurfaceHolder.lockCanvas() and getting null as a result too often.
From the docs on SurfaceHolder.lockCanvas()
If you call this repeatedly when the Surface is not ready (before
Callback.surfaceCreated or after Callback.surfaceDestroyed), your
calls will be throttled to a slow rate in order to avoid consuming
CPU.
So the OS was throttling calls by putting my threads to sleep.
I fixed it by updating the code in GOLThread.run() to have
Canvas c = null;
try {
c = mSurfaceHolder.lockCanvas();
if (c == null) {
// Pause here so that our calls do not get throttled by the
// OS for calling lockCanvas too often.
pause();
} else {
synchronized (GOLLock) {
if (gameOfLife != null) {
gameOfLife.drawAndUpdate(c);
} else {
pause();
}
}
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
I have an android application that employs a ViewPager with two pages
When the activity first displays i would like to present each page in turn to the user so that they know they can swipe between to two views.
I have failed to find any docs describing how to do this. I have discovered PageTransformations which sounded promising but the user has to swipe first.
I need my two pages to scroll automatically as soon as the first page in the ViewPager displays.
how can a achieve the desired result?
You can use Timer for this purpose. The following code is self explanatory:
// ---------------------------------------------------------------------------
Timer timer;
int page = 1;
public void pageSwitcher(int seconds) {
timer = new Timer(); // At this line a new Thread will be created
timer.scheduleAtFixedRate(new RemindTask(), 0, seconds * 1000); // delay
// in
// milliseconds
}
// this is an inner class...
class RemindTask extends TimerTask {
#Override
public void run() {
// As the TimerTask run on a seprate thread from UI thread we have
// to call runOnUiThread to do work on UI thread.
runOnUiThread(new Runnable() {
public void run() {
if (page > 4) { // In my case the number of pages are 5
timer.cancel();
// Showing a toast for just testing purpose
Toast.makeText(getApplicationContext(), "Timer stoped",
Toast.LENGTH_LONG).show();
} else {
mViewPager.setCurrentItem(page++);
}
}
});
}
}
// ---------------------------------------------------------------------------
Note 1: Make sure that you call pageSwitcher method after setting up adapter to the viewPager properly inside onCreate method of your activity.
Note 2: The viewPager will swipe every time you launch it. You have to handle it so that it swipes through all pages only once (when the user is viewing the viewPager first time)
Note 3: If you further want to slow the scrolling speed of the viewPager, you can follow this answer on StackOverflow.
Tell me in the comments if that could not help you...
The question is old but I hope it helps someone
My solution using Runnable
Short answer
Runnable runnable = new Runnable() {
public void run() {
if (myAdapter.getCount() == page) {
page = 0;
} else {
page++;
}
viewPager.setCurrentItem(page, true);
handler.postDelayed(this, delay);
}
};
Long answer
Using in an activity
public class activity extends AppCompatActivity {
private Handler handler;
private int delay = 5000; //milliseconds
private ViewPager viewPager;
private int page = 0;
private MyAdapter myAdapter;
Runnable runnable = new Runnable() {
public void run() {
if (myAdapter.getCount() == page) {
page = 0;
} else {
page++;
}
viewPager.setCurrentItem(page, true);
handler.postDelayed(this, delay);
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler();
viewPager = (ViewPager) findViewById(R.id.viewPager);
myAdapter = new MyAdapter(getSupportFragmentManager());
viewPager.setAdapter(myAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
page = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
protected void onResume() {
super.onResume();
handler.postDelayed(runnable, delay);
}
#Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(runnable);
}
}
I've created a open source project on github, which implements a auto scroll ViewPager, Example diagram below:
use
<cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
replace
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
call
startAutoScroll() to start auto scroll.
stopAutoScroll() to stop auto scroll.
More: https://github.com/Trinea/android-auto-scroll-view-pager
Here is autoscroll view pager
package com.otapp.net.view;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.Interpolator;
import android.widget.Scroller;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
public class AutoScrollViewPager extends ViewPager {
public static final int DEFAULT_INTERVAL = 1500;
public static final int LEFT = 0;
public static final int RIGHT = 1;
public static final int SLIDE_BORDER_MODE_NONE = 0;
public static final int SLIDE_BORDER_MODE_CYCLE = 1;
public static final int SLIDE_BORDER_MODE_TO_PARENT = 2;
private long interval = DEFAULT_INTERVAL;
private int direction = RIGHT;
private boolean isCycle = true;
private boolean stopScrollWhenTouch = true;
private int slideBorderMode = SLIDE_BORDER_MODE_NONE;
private boolean isBorderAnimation = true;
private double autoScrollFactor = 1.0;
private double swipeScrollFactor = 1.0;
private Handler handler;
private boolean isAutoScroll = false;
private boolean isStopByTouch = false;
private float touchX = 0f, downX = 0f;
private float touchY = 0f;
private CustomDurationScroller scroller = null;
public static final int SCROLL_WHAT = 0;
public AutoScrollViewPager(Context paramContext) {
super(paramContext);
init();
}
public AutoScrollViewPager(Context paramContext, AttributeSet paramAttributeSet) {
super(paramContext, paramAttributeSet);
init();
}
private void init() {
handler = new MyHandler(this);
setViewPagerScroller();
}
/**
* start auto scroll, first scroll delay time is {#link #getInterval()}
*/
public void startAutoScroll() {
isAutoScroll = true;
sendScrollMessage((long) (interval + scroller.getDuration() / autoScrollFactor * swipeScrollFactor));
}
/**
* start auto scroll
*
* #param delayTimeInMills first scroll delay time
*/
public void startAutoScroll(int delayTimeInMills) {
isAutoScroll = true;
sendScrollMessage(delayTimeInMills);
}
/**
* stop auto scroll
*/
public void stopAutoScroll() {
isAutoScroll = false;
handler.removeMessages(SCROLL_WHAT);
}
/**
* set the factor by which the duration of sliding animation will change while swiping
*/
public void setSwipeScrollDurationFactor(double scrollFactor) {
swipeScrollFactor = scrollFactor;
}
/**
* set the factor by which the duration of sliding animation will change while auto scrolling
*/
public void setAutoScrollDurationFactor(double scrollFactor) {
autoScrollFactor = scrollFactor;
}
private void sendScrollMessage(long delayTimeInMills) {
/** remove messages before, keeps one message is running at most **/
handler.removeMessages(SCROLL_WHAT);
handler.sendEmptyMessageDelayed(SCROLL_WHAT, delayTimeInMills);
}
/**
* set ViewPager scroller to change animation duration when sliding
*/
private void setViewPagerScroller() {
try {
Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
scrollerField.setAccessible(true);
Field interpolatorField = ViewPager.class.getDeclaredField("sInterpolator");
interpolatorField.setAccessible(true);
scroller = new CustomDurationScroller(getContext(), (Interpolator) interpolatorField.get(null));
scrollerField.set(this, scroller);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* scroll only once
*/
public void scrollOnce() {
PagerAdapter adapter = getAdapter();
int currentItem = getCurrentItem();
int totalCount;
if (adapter == null || (totalCount = adapter.getCount()) <= 1) {
return;
}
int nextItem = (direction == LEFT) ? --currentItem : ++currentItem;
if (nextItem < 0) {
if (isCycle) {
setCurrentItem(totalCount - 1, isBorderAnimation);
}
} else if (nextItem == totalCount) {
if (isCycle) {
setCurrentItem(0, isBorderAnimation);
}
} else {
setCurrentItem(nextItem, true);
}
}
/**
* <ul>
* if stopScrollWhenTouch is true
* <li>if event is down, stop auto scroll.</li>
* <li>if event is up, start auto scroll again.</li>
* </ul>
*/
boolean consumeTouch = false;
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int action = MotionEventCompat.getActionMasked(ev);
if (stopScrollWhenTouch) {
if ((action == MotionEvent.ACTION_DOWN) && isAutoScroll) {
isStopByTouch = true;
stopAutoScroll();
} else if (ev.getAction() == MotionEvent.ACTION_UP && isStopByTouch) {
startAutoScroll();
}
}
if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT || slideBorderMode == SLIDE_BORDER_MODE_CYCLE) {
touchX = ev.getX();
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
downX = touchX;
touchY = ev.getY();
} else if (action == MotionEvent.ACTION_UP) {
consumeTouch = Math.abs(touchY - ev.getY()) > 0;
}
int currentItem = getCurrentItem();
PagerAdapter adapter = getAdapter();
int pageCount = adapter == null ? 0 : adapter.getCount();
/**
* current index is first one and slide to right or current index is last one and slide to left.<br/>
* if slide border mode is to parent, then requestDisallowInterceptTouchEvent false.<br/>
* else scroll to last one when current item is first one, scroll to first one when current item is last
* one.
*/
if ((currentItem == 0 && downX <= touchX) || (currentItem == pageCount - 1 && downX >= touchX)) {
if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT) {
getParent().requestDisallowInterceptTouchEvent(false);
} else {
if (pageCount > 1) {
setCurrentItem(pageCount - currentItem - 1, isBorderAnimation);
}
getParent().requestDisallowInterceptTouchEvent(true);
}
return super.dispatchTouchEvent(ev);
}
}
if (consumeTouch) {
getParent().requestDisallowInterceptTouchEvent(true);
} else {
getParent().requestDisallowInterceptTouchEvent(false);
if (stopScrollWhenTouch)
startAutoScroll();
}
return super.dispatchTouchEvent(ev);
}
private static class MyHandler extends Handler {
private final WeakReference<AutoScrollViewPager> autoScrollViewPager;
public MyHandler(AutoScrollViewPager autoScrollViewPager) {
this.autoScrollViewPager = new WeakReference<AutoScrollViewPager>(autoScrollViewPager);
}
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SCROLL_WHAT:
AutoScrollViewPager pager = this.autoScrollViewPager.get();
if (pager != null) {
pager.scroller.setScrollDurationFactor(pager.autoScrollFactor);
pager.scrollOnce();
pager.scroller.setScrollDurationFactor(pager.swipeScrollFactor);
pager.sendScrollMessage(pager.interval + pager.scroller.getDuration());
}
default:
break;
}
}
}
public long getInterval() {
return interval;
}
public void setInterval(long interval) {
this.interval = interval;
}
public int getDirection() {
return (direction == LEFT) ? LEFT : RIGHT;
}
public void setDirection(int direction) {
this.direction = direction;
}
public boolean isCycle() {
return isCycle;
}
public void setCycle(boolean isCycle) {
this.isCycle = isCycle;
}
public boolean isStopScrollWhenTouch() {
return stopScrollWhenTouch;
}
public void setStopScrollWhenTouch(boolean stopScrollWhenTouch) {
this.stopScrollWhenTouch = stopScrollWhenTouch;
}
public int getSlideBorderMode() {
return slideBorderMode;
}
public void setSlideBorderMode(int slideBorderMode) {
this.slideBorderMode = slideBorderMode;
}
public boolean isBorderAnimation() {
return isBorderAnimation;
}
public void setBorderAnimation(boolean isBorderAnimation) {
this.isBorderAnimation = isBorderAnimation;
}
public class CustomDurationScroller extends Scroller {
private double scrollFactor = 1;
public CustomDurationScroller(Context context) {
super(context);
}
public CustomDurationScroller(Context context, Interpolator interpolator) {
super(context, interpolator);
}
// #SuppressLint("NewApi")
// public CustomDurationScroller(Context context, Interpolator interpolator, boolean flywheel){
// super(context, interpolator, flywheel);
// }
public void setScrollDurationFactor(double scrollFactor) {
this.scrollFactor = scrollFactor;
}
#Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
super.startScroll(startX, startY, dx, dy, (int) (duration * scrollFactor));
}
}
}
Here is xml implementation
Here is class file implementation
MovieFeaturedAdapter mMovieFeaturedAdapter = new MovieFeaturedAdapter(getActivity(), mCurrentMovies);
vpFeatured.setAdapter(mMovieFeaturedAdapter);
Below method is use to switch pages automatically after some time (you can modify time as per your requirement)
private void timer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (currentPage == NUM_PAGES - 1) {
currentPage = 0;
}
view.setCurrentItem(currentPage++, true);
}
});
}
}, 500, 5000);
}
if want to endless scroll in viewpager use infinite scroll viewpager class from below provided link and do minor changes (remove condition) in Runnable interface.
runOnUiThread(new Runnable() {
#Override
public void run() {
view.setCurrentItem(currentPage++, true);
}
});
also,don't forget to cancel timer on Destroy view.
You can use setCurrentItem to change page
If you want to autoplay viewpager pages but above all solution is correct but after autoplay first item consume delay time but it is wrong after autoplay current item switch quickly. I am adding my code below it is working correctly autoplay/pause.
#Override
public void onClick(View v) {
if (!isAutoPlay) {
img_autoplay.setImageResource(R.drawable.pause);
int currentcount = getModel().getCurrentIndex();
currentcount++;
getMainImage().setCurrentItem(currentcount);
autoPlay(getMainImage());
isAutoPlay = true;
} else {
img_autoplay.setImageResource(R.drawable.auto_play);
isAutoPlay = false;
}
}
});
and here is method:
viewPager.postDelayed(new Runnable() {
#Override
public void run() {
try {
if (myAdapter != null
&& viewPager.getAdapter().getCount() > 0
&& isAutoPlay) {
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
int currentcount = getModel().getCurrentIndex();
currentcount++;
viewPager.setCurrentItem(currentcount);
if (getModel().isLastCard()) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
isAutoPlay = false;
packFinished();
getWindow()
.clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}, 6000);
}
autoPlay(viewPager);
}
} catch (Exception e) {
}
}
}, 6000);
If you are going to switch page automatically then you should disable paging/swiping on ViewPager because if you touch on page and that time page switching then it's not look good means you observed page struck.
To disable paging/swiping on ViewPager,you need to add below code snippet with you custom view pager.
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.Interpolator;
import java.lang.reflect.Field;
public class ViewPagerCustomDuration extends ViewPager {
private boolean swipeable = false;
public ViewPagerCustomDuration(Context context) {
super(context);
postInitViewPager();
}
public ViewPagerCustomDuration(Context context, AttributeSet attrs) {
super(context, attrs);
postInitViewPager();
}
public void setSwipeable(boolean swipeable) {
this.swipeable = swipeable;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (this.swipeable) {
return super.onTouchEvent(event);
}
return false;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.swipeable) {
return super.onInterceptTouchEvent(event);
}
return false;
}
private ScrollerCustomDuration mScroller = null;
/**
* Override the Scroller instance with our own class so we can change the
* duration
*/
private void postInitViewPager() {
try {
Field scroller = ViewPager.class.getDeclaredField("mScroller");
scroller.setAccessible(true);
Field interpolator = ViewPager.class.getDeclaredField("sInterpolator");
interpolator.setAccessible(true);
mScroller = new ScrollerCustomDuration(getContext(),
(Interpolator) interpolator.get(null));
scroller.set(this, mScroller);
} catch (Exception e) {
}
}
/**
* Set the factor by which the duration will change
*/
public void setScrollDurationFactor(double scrollFactor) {
mScroller.setScrollDurationFactor(scrollFactor);
}
}
after that,call method from view pager object.
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
ViewPagerCustomDuration viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_3);
viewPager = (ViewPagerCustomDuration) findViewById(R.id.viewpager);
viewPager.setScrollDurationFactor(2);
viewPager.setAdapter(new CustomPagerAdapter(this));
viewPager.setSwipeable(false);
pageSwitcher(5);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
Timer timer;
int page = 1;
public void pageSwitcher(int seconds) {
timer = new Timer(); // At this line a new Thread will be created
timer.scheduleAtFixedRate(new RemindTask(), 0, seconds * 1000); // delay
// in
// milliseconds
}
// this is an inner class...
class RemindTask extends TimerTask {
#Override
public void run() {
// As the TimerTask run on a seprate thread from UI thread we have
// to call runOnUiThread to do work on UI thread.
runOnUiThread(new Runnable() {
public void run() {
if (page > 4) { // In my case the number of pages are 5
// timer.cancel();
page = 0;
viewPager.setCurrentItem(page++);
// Showing a toast for just testing purpose
Toast.makeText(getApplicationContext(), "Timer stoped",
Toast.LENGTH_LONG).show();
} else {
viewPager.setCurrentItem(page++);
}
}
});
}
}
Scroller class for scroll page smoothly
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.animation.Interpolator;
import android.widget.Scroller;
public class ScrollerCustomDuration extends Scroller {
private double mScrollFactor = 1;
public ScrollerCustomDuration(Context context) {
super(context);
}
public ScrollerCustomDuration(Context context, Interpolator interpolator) {
super(context, interpolator);
}
#SuppressLint("NewApi")
public ScrollerCustomDuration(Context context, Interpolator interpolator, boolean flywheel) {
super(context, interpolator, flywheel);
}
/**
* Set the factor by which the duration will change
*/
public void setScrollDurationFactor(double scrollFactor) {
mScrollFactor = scrollFactor;
}
#Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
super.startScroll(startX, startY, dx, dy, (int) (duration * mScrollFactor));
}
}
For new viewPage2 you can use below code
fun ViewPager2.enableAutoScroll(totalPages: Int): Timer {
val autoTimerTask = Timer()
var currentPageIndex = currentItem
autoTimerTask.schedule(object : TimerTask() {
override fun run() {
currentItem = currentPageIndex++
if (currentPageIndex == totalPages) currentPageIndex = 0
}
}, 0, DELAY_FOUR_SECONDS)
// Stop auto paging when user touch the view
getRecyclerView().setOnTouchListener { _, event ->
if (event.action == MotionEvent.ACTION_DOWN) autoTimerTask.cancel()
false
}
return autoTimerTask // Return the reference for cancel
}
fun ViewPager2.getRecyclerView(): RecyclerView {
val recyclerViewField = ViewPager2::class.java.getDeclaredField("mRecyclerView")
recyclerViewField.isAccessible = true
return recyclerViewField.get(this) as RecyclerView
}