Use a Variable from external Library in an Activity - java

I am trying to use the variable "mCurrentPage" from an external Library in an Activity. This Library uses the views from a FrameLayout and shows them as book pages which you can swipe. What I want to do is to execute something IF an X view of the FrameLayout is on the front. (please not bringToFront())
I have tried with getElevation() but it requires API > 21.
Actually the variable "mCurrentPage" from that code does the job. but I need to use it (or imitate it) in other activities as well, I just can´t figure out how does this variable work and where does it get their values from in order to tell what´s the current view in the front.
public class PageTurnLayout extends FrameLayout {
private Point mLastTouchPoint;
private Rect mTopViewRect;
private Rect mBottomViewRect;
private Paint mPaint;
private int mCurrentPage;
private int mPageTouchSlop;
private boolean mIsTurning;
private PageTurnDirection mDirection;
private float mFirstX;
private Handler mHandler = new Handler();
public PageTurnLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PageTurnLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public PageTurnLayout(Context context) {
super(context);
init();
}
private void init() {
setWillNotDraw(false);
mPaint = new Paint();
mBottomViewRect = new Rect();
mTopViewRect = new Rect();
mPageTouchSlop = (int) getResources().getDimension(R.dimen.touch_start_padding);
}
protected boolean isTouchAPageTurnStart(MotionEvent ev) {
if (ev.getAction() != MotionEvent.ACTION_DOWN)
return false;
return isTouchNearEdge(ev);
}
protected boolean isTouchNearEdge(MotionEvent ev) {
if (Math.abs(ev.getX() - getMeasuredWidth()) < mPageTouchSlop)
return true;
else if (ev.getX() < mPageTouchSlop)
return true;
return false;
}
protected PageTurnDirection getPageTurnDirection(MotionEvent ev) {
if(mFirstX - ev.getX() == 0.0f)
return null;
PageTurnDirection direction = mFirstX - ev.getX() > 0 ? PageTurnDirection.LEFT : PageTurnDirection.RIGHT;
return direction;
}
protected boolean shouldTurn() {
if(mDirection == null)
return false;
if(mDirection == PageTurnDirection.LEFT && mCurrentPage == getChildCount() - 1)
return false;
else if(mDirection == PageTurnDirection.RIGHT && mCurrentPage == 0)
return false;
return true;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN && !mIsTurning) {
mIsTurning = isTouchAPageTurnStart(event);
if (!mIsTurning) {
return false;
} else {
invalidate();
mLastTouchPoint = new Point((int) event.getX(), (int) event.getY());
mFirstX = event.getX();
return true;
}
} else if (event.getAction() == MotionEvent.ACTION_MOVE && mIsTurning) {
if(mDirection == null) {
//get the page turn direction
mDirection = getPageTurnDirection(event);
//if we shouldn't turn then abort everything and reset it
if(!shouldTurn()) {
mDirection = null;
mIsTurning = false;
return false;
}
}
mLastTouchPoint = new Point((int) event.getX(), (int) event.getY());
invalidate();
} else if (event.getAction() == MotionEvent.ACTION_UP && mIsTurning) {
int halfWidth = getMeasuredWidth() / 2;
if (mLastTouchPoint.x > halfWidth) {
final Runnable animationRunnable = new Runnable() {
public void run() {
mLastTouchPoint.x += 20;
invalidate();
if (mLastTouchPoint.x < getMeasuredWidth())
mHandler.post(this);
else {
mIsTurning = false;
if (mDirection == PageTurnDirection.RIGHT)
mCurrentPage--;
mDirection = null;
}
}
};
mHandler.post(animationRunnable);
} else {
final Runnable animationRunnable = new Runnable() {
public void run() {
mLastTouchPoint.x -= 20;
invalidate();
if (mLastTouchPoint.x > -(getMeasuredWidth() / 2)) {
mHandler.post(this);
} else {
mIsTurning = false;
if (mDirection == PageTurnDirection.LEFT)
mCurrentPage++;
mDirection = null;
}
}
};
mHandler.post(animationRunnable);
}
}
return true;
}

Related

Android, java, view.setOnTouchListener

I had a recyclerview with an adapter and everything was cool. I added view.setOnTouchListener so that I could scroll this recyclerview along with animation and other elements on 1 screen from left to right. But after that, scrolling up and down broke in recyclerview, and onclicklistener on the elements inside it stopped working. What to do and how to fix this conflict?
At the moment I can put return false in the public boolean onTouch (View v, MotionEvent event) method; instead of return gestureDetector.onTouchEvent (event); and get a working scrolling up and down back, but left-right stops working. I can do simultaneous scrolling as in ios, when scrolling of tablecloths and collections did not break when adding the svayp to the left-right.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {
public void onSwipeRight() {
choseold = chosenow;
chosenow = chosenow - 1;
if (chosenow <= 0) {
chosenow = 5;
choseold = 6;
}
swipe();
}
public void onSwipeLeft() {
choseold = chosenow;
chosenow = chosenow + 1;
if (chosenow >= 6) {
chosenow = 1;
choseold = 0;
}
swipe();
}
});
view.setFocusableInTouchMode(true);
MyAdapterlang = new MyAdapterLang(MainActivity.this, yaziki1, yaziki2, flagi);
RVlang.setAdapter(MyAdapterlang);
mLayoutManager = new LinearLayoutManager(this);
RV1.setLayoutManager(mLayoutManager);
MyAdapter = new MyAdapterApps(MainActivity.this, childs, childs2);
RV1.setAdapter(MyAdapter);
}
}
class OnSwipeTouchListener implements View.OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener (Context ctx){
gestureDetector = new GestureDetector(ctx, new GestureListener());
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
//return false;
}
/*public boolean onTouch(final View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
y1 = event.getY();
break;
case MotionEvent.ACTION_MOVE:
y2 = event.getY();
float deltaY = y2 - y1;
if (Math.abs(deltaY) > MIN_DISTANCE) {
return false;
} else {
return gestureDetector.onTouchEvent(event);
}
}
return gestureDetector.onTouchEvent(event);
}
private float y1, y2;
private static final int MIN_DISTANCE = 50;*/
private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
return true;
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
return false;
}
}
public void onSwipeRight() {
}
public void onSwipeLeft() {
}
}
Here in ios, for example, is very simple and does not break the scrolling of collections:
- (void)viewDidLoad {
UISwipeGestureRecognizer * swipeleft=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:#selector(swipeleft:)];
swipeleft.direction=UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeleft];
UISwipeGestureRecognizer * swiperight=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:#selector(swiperight:)];
swiperight.direction=UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:swiperight];
}
-(void)swipeleft:(UISwipeGestureRecognizer*)gestureRecognizer
{
if (self.currentnew <= 3) {
self.whatpress = 1;
[self.buttonnew sendActionsForControlEvents:UIControlEventTouchUpInside];
}
}
-(void)swiperight:(UISwipeGestureRecognizer*)gestureRecognizer
{
if ((self.currentnew >= 1) && (self.currentnew <= 3)) {
self.whatpress = 2;
[self.buttonnew sendActionsForControlEvents:UIControlEventTouchUpInside];
}
}
Here is a video:
https://2ch.hk/pr/src/1314926/15464190246250.mp4 https://2ch.hk/pr/src/1314926/15464193253190.mp4
If you only want to hook into default touch handling implementation you must return false here
#Override
public boolean onTouch(View v, MotionEvent event) {
gestureDetector.onTouchEvent(event);//Idk if it is needed or not - out of scope
return false;
}
Otherwise touch event will be considered as consumed and wont be propagated to other handlers (that handles scrolling, clicking etc. - all that stuff that stops working for you)

Android set on drag listener is showing error

I am developing an android app using drag and drop. And also I am using an a broadcast receiver for screen on. When I am using setOnDragListener It shows an error:
java.lang.RuntimeException: Error receiving broadcast Intent { act=init view flg=0x10 } in com.app.lockscreenlibrary.LockBroadcastReceiver#f22ed7d
Can anybody please help me solve the issue? Here is my code:
ActivityView.java
public class ActivityView extends FrameLayout {
public LinearLayout drop;
TextView text,sucess;
int total , failure = 0;
ImageView viewDrop;
private GestureDetector gestureDetector;
private Context mContext;
Button btnUnlock;
Button btn1;
private int CLICK_ACTION_THRESHHOLD = 200;
private float startX;
private float startY;
public ActivityView(Context context) {
this(context, null);
}
public ActivityView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ActivityView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(final Context context) {
mContext = context;
View view = inflate(context,R.layout.activity_view,null);
gestureDetector = new GestureDetector(context, new SingleTapConfirm());
drop = (LinearLayout)findViewById(R.id.bottomlinear);
sucess = (TextView)findViewById(R.id.Sucess);
drop.setOnDragListener();
drop.setOnDragListener(new View.OnDragListener() {
#Override
public boolean onDrag(View v, DragEvent event) {
//return false;
final int action = event.getAction();
switch(action) {
case DragEvent.ACTION_DRAG_STARTED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DROP:{
failure = failure+1;
return(true);
}
case DragEvent.ACTION_DRAG_ENDED:{
total = total +1;
int suc = total - failure;
sucess.setText("Sucessful Drops :"+suc);
text.setText("Total Drops: "+total);
return(true);
}
default:
break;
}
return true;
}
});
btnUnlock = (Button) view.findViewById(R.id.unlock);
btnUnlock.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
LockHelper.getLockLayer().unlock();
}
});
btn01 = (Button) view.findViewById(R.id.btn0);
btn1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("LockView", "onTouch");
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
startY = event.getY();
break;
case MotionEvent.ACTION_UP:
float endX = event.getX();
float endY = event.getY();
if (isAClick(startX, endX, startY, endY)) {
Log.d("LockView", "clicked");
} else {
}
break;
}
v.getParent().requestDisallowInterceptTouchEvent(true); //specific to my project
return false;
}
});
addView(view);
}
}
}
private class SingleTapConfirm extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapUp(MotionEvent event) {
Log.d("LockView", "clicked1");
return true;
}
}
private boolean isAClick(float startX, float endX, float startY, float endY) {
float differenceX = Math.abs(startX - endX);
float differenceY = Math.abs(startY - endY);
if (differenceX > CLICK_ACTION_THRESHHOLD/* =5 */ || differenceY > CLICK_ACTION_THRESHHOLD) {
return false;
}
return true;
}
}
LockBroadcastReceiver.java
final public class LockBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = LockBroadcastReceiver.class.getSimpleName();
private volatile boolean bInterruptSupervisor = false;
private ScheduledThreadPoolExecutor mExecutor;
private FutureRunnable mSupervisorRunnable;
private static final int SCHEDULE_TASK_NUMBER = 3;
private PhoneStateChange mPhoneStateChangeCallback;
public void assignPhoneStateChangeCallback(PhoneStateChange phoneStateChangeCallback) {
mPhoneStateChangeCallback = phoneStateChangeCallback;
}
#Override public void onReceive(Context context, Intent intent) {
String mAction = intent.getAction();
//DU.sd("broadcast -----The Intent Action is: ", "" + mAction);
switch (mAction) {
case LockHelper.INIT_VIEW_FILTER:
LockHelper.INSTANCE.initLockViewInBackground(context);
break;
case Intent.ACTION_SCREEN_ON:
refreshBatteryInfo();
bringLockViewBackTopIfNot();
break;
case CoreIntent.ACTION_SCREEN_LOCKER_UNLOCK:
shutdownScheduleExecutor();
break;
case LockHelper.START_SUPERVISE:
bInterruptSupervisor = false;
supervise(context.getApplicationContext());
break;
case LockHelper.STOP_SUPERVISE:
bInterruptSupervisor = true;
break;
case LockHelper.SHOW_SCREEN_LOCKER:
//DU.sd("broadcast", "locker received");
case Intent.ACTION_SCREEN_OFF:
LockHelper.INSTANCE.initialize(context);
LockHelper.INSTANCE.getLockLayer().lock();
bInterruptSupervisor = true;
break;
case Intent.ACTION_POWER_CONNECTED:
//LockHelper.INSTANCE.getLockView().batteryChargingAnim();
break;
case Intent.ACTION_POWER_DISCONNECTED:
//LockHelper.INSTANCE.getLockView().batteryChargingAnim();
break;
case Intent.ACTION_SHUTDOWN:
break;
case "android.intent.action.PHONE_STATE":
TelephonyManager tm =
(TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
switch (tm.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING:
mPhoneStateChangeCallback.ringing();
Log.i(TAG, "RINGING :" + intent.getStringExtra("incoming_number"));
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
mPhoneStateChangeCallback.offHook();
//DU.sd(TAG, "off hook");
break;
case TelephonyManager.CALL_STATE_IDLE:
mPhoneStateChangeCallback.idle();
Log.i(TAG, "incoming IDLE");
break;
}
break;
default:
break;
}
}
abstract class FutureRunnable implements Runnable {
private Future<?> future;
public Future<?> getFuture() {
return future;
}
public void setFuture(Future<?> future) {
this.future = future;
}
}
public void supervise(final Context context) {
//DU.sd("service", "supervise");
initScheduleExecutor();
if (mSupervisorRunnable == null) {
mSupervisorRunnable = new FutureRunnable() {
public void run() {
if (bInterruptSupervisor) getFuture().cancel(true);
boolean cameraRunning = false;
Camera _camera = null;
try {
_camera = Camera.open();
cameraRunning = _camera == null;
} catch (Exception e) {
// fail to open camera, secure to ignore exception
//DU.sd("camera exception on supervise");
cameraRunning = true;
} finally {
if (_camera != null) {
_camera.release();
getFuture().cancel(true);
context.sendBroadcast(new Intent(LockHelper.SHOW_SCREEN_LOCKER));
}
}
if (!cameraRunning) context.sendBroadcast(new Intent(LockHelper.SHOW_SCREEN_LOCKER));
}
};
}
Future<?> future =
mExecutor.scheduleAtFixedRate(mSupervisorRunnable, 2000, 500, TimeUnit.MILLISECONDS);
mSupervisorRunnable.setFuture(future);
}
private void bringLockViewBackTopIfNot() {
initScheduleExecutor();
mExecutor.scheduleAtFixedRate(new Runnable() {
#Override public void run() {
LockHelper.INSTANCE.getLockLayer().requestFullScreen();
}
}, 1000, 1000, TimeUnit.MILLISECONDS);
}
private void refreshBatteryInfo() {
initScheduleExecutor();
mExecutor.scheduleAtFixedRate(new Runnable() {
#Override public void run() {
//LockHelper.INSTANCE.getLockView().refreshBattery();
}
}, 2, 2, TimeUnit.MINUTES);
}
private void initScheduleExecutor() {
if (mExecutor == null) {
synchronized (this) {
if (mExecutor == null) mExecutor = new ScheduledThreadPoolExecutor(SCHEDULE_TASK_NUMBER);
}
}
}
public synchronized void shutdownScheduleExecutor() {
if (mExecutor == null) return;
mExecutor.shutdown();
mExecutor = null;
}
}
LockHelper.java
public enum LockHelper implements SwipeEvent {
INSTANCE;
private static Context mContext;
private final int UNLOCK = 830;
private final int UNLOCK_WITH_PASSWORD = 831;
private final int SWITCH_TO_GUEST = 345;
public static final String INIT_VIEW_FILTER = "init view";
public static final String START_SUPERVISE = "start supervise";
public static final String STOP_SUPERVISE = "stop supervise";
public static final String SHOW_SCREEN_LOCKER = "show screen locker";
private static LockView mLockView;
private static LockLayer mLockLayer;
public void initialize(Context context) {
initContextViewAndLayer(context);
loadLockView(context);
}
/**
* #throws NullPointerException if not init
*/
public static LockView getLockView() {
if (mLockView == null)
throw new NullPointerException("init first");
return mLockView;
}
/**
* #throws NullPointerException if not init
*/
public static LockLayer getLockLayer() {
if (mLockLayer == null)
throw new NullPointerException("init first");
return mLockLayer;
}
/**
* #throws NullPointerException if context == null
*/
public void initLockViewInBackground(final Context context) {
if (context == null)
throw new NullPointerException("context == null, assign first");
if (mLockView == null || mLockLayer == null)
initContextViewAndLayer(context);
}
public void initContextViewAndLayer(Context context) {
if (mContext == null)
synchronized (this) {
if (mContext == null)
mContext = context;
}
//init layout view
if (mLockView == null)
synchronized (this) {
if (mLockView == null)
mLockView = new LockView(context);
}
//init lock layer
if (mLockLayer == null)
synchronized (this) {
if (mLockLayer == null)
mLockLayer = LockLayer.getInstance(context, mLockView);
}
}
private volatile boolean mIsInitialized = false;
public void loadLockView(Context context) {
mLockView.showLockHome();
if( !mIsInitialized){
//mLockView.assignSwipeEvent(this);
//
//mLockView.assignDirectionOperator(new SwipeWithAnimListener.DirectionOperator() {
// #Override
// public void up() {
// }
//
// #Override
// public void down() {
//
// }
//
// #Override
// public void left() {
// if(!mLockView.leftSlidable()) return;
//
// mHandler.sendEmptyMessage(UNLOCK);
// }
//
// #Override
// public void right() {
// if(!mLockView.rightSlidable()) return;
//
// mHandler.sendEmptyMessage(UNLOCK);
// }
//});
// mLockView.assignPinCodeRuler(new PinCodeView.UnlockInterface() {
// #Override
// public void onUnlock(String password) {
//
// Message msg = new Message();
// msg.what = UNLOCK_WITH_PASSWORD;
// msg.obj = password;
// mHandler.sendMessage(msg);
// }
//
// #Override
// public void onBack() {
// mLockView.switchBackToCenterFromBottom();
// }
// });
mIsInitialized = true;
}
mLockLayer.lock();
showLockLayer();
}
private Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UNLOCK:
//DU.sd("handler", "unlock");
unlock();
break;
case UNLOCK_WITH_PASSWORD:
if (!(msg.obj instanceof String)) break;
String password = (String) msg.obj;
switchUserIfExistOrAlertUser(password);
break;
default:
break;
}
}
};
private void unlock() {
mLockLayer.unlock();
//mLockView.stopShimmer();
mContext.sendBroadcast(new Intent(LockHelper.STOP_SUPERVISE));
mContext.sendBroadcast(new Intent(CoreIntent.ACTION_SCREEN_LOCKER_UNLOCK));
}
private void switchUserIfExistOrAlertUser(String password) {
if (TextUtils.isEmpty(password)) {
wrong();
return;
}
if (!password.equals("1234")) {
wrong();
return;
}
unlockScreenAndResetPinCode();
}
private void unlockScreenAndResetPinCode() {
unlock();
// mLockView.resetPinCodeView();
}
private void wrong() {
}
public static final String INTENT_KEY_WITH_SECURE = "with_secure";
#Override
public <S, T> void onSwipe(S s, T t) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
LockHelper.INSTANCE.getLockLayer().removeLockView();
}
}, 1000);
//triggerCameraWithSecure(mContext, !(t instanceof Boolean) || (Boolean) t);
}
private void triggerCameraWithSecure(Context context, boolean withSecure) {
//if (!CameraHelper.hasCameraHardware(context)) return;
//
//try {
// CameraHelper.cameraStrategy(context, withSecure);
//} catch (Exception e) {
// // may cannot open
// e.printStackTrace();
// showLockLayer();
//}
//
//context.sendBroadcast(new Intent(LockHelper.START_SUPERVISE));
}
private void showLockLayer() {
mLockView.showLockHome();
mLockLayer.bringBackLockView();
}
public void vibrate(long milliseconds) {
if (mContext == null) return;
Vibrator v = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(milliseconds == 0 ? 500 : milliseconds);
}
}
There is no problem with the boradcast receiver per se. You have a clear exception in your code
java.lang.ClassCastException: com.happiness.lockscreenlibrary.LockScreenService cannot be cast to android.view.View$OnDragListener at
You are trying to cast an incompatible class type to another. I could not see that part of code in what you pasted here. So, please try to figure that out. Basically the code you are executing on receiving the broadcast has a bug, nothing with the receiver as such

android - animate on swipe

In my new program I need objects that can be swiped to the side. I already have my animation, which is working and I tried to detect the swiping of the user in another class. The problem I have is that I don't know how to connect them. When the swipe gesture is correctly recognized a specific animation should start.
My AnimatedViewClass:
private Runnable r = new Runnable() {
#Override
public void run() {
if(continueAnimation) {
invalidate();
}
}
};
protected void onDraw(Canvas c) {
if (x<0) {
x = this.getWidth()/2-100;
y = this.getHeight()/2-100;
}
else {
x += xVelocity;
if ((x > this.getWidth() - ball.getBitmap().getWidth()) || (x < 0)) {
boolean continueAnimation = false;
}
}
c.drawBitmap(ball.getBitmap(), x, y, null);
if(continueAnimation)
{
h.postDelayed(r, FRAME_RATE);
}
else {
x = this.getWidth()-ball.getBitmap().getWidth();
}
}
My SwipeTouchListener:
public class OnSwipeTouchListener implements OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener (Context ctx){
gestureDetector = new GestureDetector(ctx, new GestureListener());
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
}
result = true;
}
else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
} else {
onSwipeTop();
}
}
result = true;
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
}
You can add GestureDetector to your view class just like this, and replace your code inside onFling()
public class AnimatedViewClass extends View {
GestureDetector gestureDetector;
public AnimatedViewClass(Context context) {
super(context);
gestureDetector = new GestureDetector(getContext(), new GestureDetectorListener());
}
#Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
private void onSwipeRight(){
// swipe right detected
// do stuff
invalidate();
}
private void onSwipeLeft(){
// swipe left detected
// do stuff
invalidate();
}
private class GestureDetectorListener extends
GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// onSwipeRight()
// onSwipeLeft()
return super.onFling(e1, e2, velocityX, velocityY);
}
#Override
public boolean onDown(MotionEvent e) {
return super.onDown(e);
}
}
private Runnable r = new Runnable() {
#Override
public void run() {
if(continueAnimation) {
invalidate();
}
}
};
protected void onDraw(Canvas c) {
if (x < 0) {
x = this.getWidth() / 2 - 100;
y = this.getHeight() / 2 - 100;
} else {
x += xVelocity;
if ((x > this.getWidth() - ball.getBitmap().getWidth()) || (x < 0)) {
boolean continueAnimation = false;
}
}
c.drawBitmap(ball.getBitmap(), x, y, null);
if (continueAnimation) {
h.postDelayed(r, FRAME_RATE);
} else {
x = this.getWidth() - ball.getBitmap().getWidth();
}
}
}

Listview with pull to refresh Scroll down to last item when adding header-view

I have created one pull to refresh listview now when I scroll or pull little bit then I have to add header view.
here my custom listview class
package com.app.refreshableList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.app.xxxxxx.R;
import com.google.android.gms.internal.el;
public class RefreshableListView extends ListView {
Boolean isScrool = false;
private View mHeaderContainer = null;
private View mHeaderView = null;
private ImageView mArrow = null;
private ProgressBar mProgress = null;
private TextView mText = null;
private float mY = 0;
private float mHistoricalY = 0;
private int mHistoricalTop = 0;
private int mInitialHeight = 0;
private boolean mFlag = false;
private boolean mArrowUp = false;
private boolean mIsRefreshing = false;
private int mHeaderHeight = 0;
private OnRefreshListener mListener = null;
private static final int REFRESH = 0;
private static final int NORMAL = 1;
private static final int HEADER_HEIGHT_DP = 62;
private static final String TAG = RefreshableListView.class.getSimpleName();
private ListViewObserver mObserver;
private View mTrackedChild;
private int mTrackedChildPrevPosition;
private int mTrackedChildPrevTop;
OnTouchListener touch;
View vHeader;
#Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mTrackedChild == null) {
if (getChildCount() > 0) {
mTrackedChild = getChildInTheMiddle();
mTrackedChildPrevTop = mTrackedChild.getTop();
mTrackedChildPrevPosition = getPositionForView(mTrackedChild);
}
} else {
boolean childIsSafeToTrack = mTrackedChild.getParent() == this
&& getPositionForView(mTrackedChild) == mTrackedChildPrevPosition;
if (childIsSafeToTrack) {
int top = mTrackedChild.getTop();
if (mObserver != null) {
float deltaY = top - mTrackedChildPrevTop;
mObserver.onScroll(deltaY);
}
mTrackedChildPrevTop = top;
} else {
mTrackedChild = null;
}
}
}
private View getChildInTheMiddle() {
return getChildAt(getChildCount() / 2);
}
public void setObserver(ListViewObserver observer) {
mObserver = observer;
}
public RefreshableListView(final Context context) {
super(context);
initialize();
}
public RefreshableListView(final Context context, final AttributeSet attrs) {
super(context, attrs);
initialize();
}
public RefreshableListView(final Context context, final AttributeSet attrs,
final int defStyle) {
super(context, attrs, defStyle);
initialize();
}
public void setOnRefreshListener(final OnRefreshListener l) {
mListener = l;
}
#Override
public void setOnTouchListener(OnTouchListener l) {
// TODO Auto-generated method stub
super.setOnTouchListener(l);
}
public void completeRefreshing() {
mProgress.setVisibility(View.INVISIBLE);
mArrow.setVisibility(View.VISIBLE);
mHandler.sendMessage(mHandler.obtainMessage(NORMAL, mHeaderHeight, 0));
mIsRefreshing = false;
invalidateViews();
}
#Override
public boolean onInterceptTouchEvent(final MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mHandler.removeMessages(REFRESH);
mHandler.removeMessages(NORMAL);
mY = mHistoricalY = ev.getY();
if (mHeaderContainer.getLayoutParams() != null) {
mInitialHeight = mHeaderContainer.getLayoutParams().height;
}
break;
}
return super.onInterceptTouchEvent(ev);
}
#Override
public boolean onTouchEvent(final MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_MOVE:
mHistoricalTop = getChildAt(0).getTop();
break;
case MotionEvent.ACTION_UP:
if (!mIsRefreshing) {
if (mArrowUp) {
startRefreshing();
mHandler.sendMessage(mHandler.obtainMessage(REFRESH,
(int) (ev.getY() - mY) / 2 + mInitialHeight, 0));
} else {
if (getChildAt(0).getTop() == 0) {
mHandler.sendMessage(mHandler.obtainMessage(NORMAL,
(int) (ev.getY() - mY) / 2 + mInitialHeight, 0));
}
}
} else {
mHandler.sendMessage(mHandler.obtainMessage(REFRESH,
(int) (ev.getY() - mY) / 2 + mInitialHeight, 0));
}
mFlag = false;
break;
}
return super.onTouchEvent(ev);
}
#Override
public boolean dispatchTouchEvent(final MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_MOVE
&& getFirstVisiblePosition() == 0) {
float direction = ev.getY() - mHistoricalY;
int height = (int) (ev.getY() - mY) / 2 + mInitialHeight;
if (height < 0) {
height = 0;
}
float deltaY = Math.abs(mY - ev.getY());
ViewConfiguration config = ViewConfiguration.get(getContext());
if (deltaY > config.getScaledTouchSlop()) {
// Scrolling downward
if (direction > 0) {
// Refresh bar is extended if top pixel of the first item is
// visible
if (getChildAt(0) != null) {
if (getChildAt(0).getTop() == 0) {
if (mHistoricalTop < 0) {
// mY = ev.getY(); // TODO works without
// this?mHistoricalTop = 0;
}
// if (isScrool == true) {
//
// } else {
// isScrool = true;
// addHeaderView(vHeader);
//
// // Animation anim = AnimationUtils.loadAnimation(
// // getContext(), R.anim.bounce_animation);
// // startAnimation(anim);
//
// smoothScrollToPosition(getChildAt(0).getTop());
// // bottom_layout.setVisibility(View.VISIBLE);
// }
// Extends refresh bar
/*****
* commented by me on 10-09-2014
*/
setHeaderHeight(height);
// Stop list scroll to prevent the list from
// overscrolling
ev.setAction(MotionEvent.ACTION_CANCEL);
mFlag = false;
}
}
} else if (direction < 0) {
// Scrolling upward
// Refresh bar is shortened if top pixel of the first item
// is
// visible
if (getChildAt(0) != null) {
if (getChildAt(0).getTop() == 0) {
setHeaderHeight(height);
// If scroll reaches top of the list, list scroll is
// enabled
if (getChildAt(1) != null
&& getChildAt(1).getTop() <= 1 && !mFlag) {
ev.setAction(MotionEvent.ACTION_DOWN);
mFlag = true;
}
}
}
}
}
mHistoricalY = ev.getY();
}
try {
return super.dispatchTouchEvent(ev);
} catch (Exception e) {
return false;
}
}
#Override
public boolean performItemClick(final View view, final int position,
final long id) {
if (position == 0) {
// This is the refresh header element
return true;
} else {
return super.performItemClick(view, position - 1, id);
}
}
private void initialize() {
LayoutInflater inflator = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vHeader = inflator.inflate(R.layout.search_header, null);
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mHeaderContainer = inflater.inflate(R.layout.refreshable_list_header,
null);
mHeaderView = mHeaderContainer
.findViewById(R.id.refreshable_list_header);
mArrow = (ImageView) mHeaderContainer
.findViewById(R.id.refreshable_list_arrow);
mProgress = (ProgressBar) mHeaderContainer
.findViewById(R.id.refreshable_list_progress);
mText = (TextView) mHeaderContainer
.findViewById(R.id.refreshable_list_text);
addHeaderView(mHeaderContainer);
mHeaderHeight = (int) (HEADER_HEIGHT_DP * getContext().getResources()
.getDisplayMetrics().density);
setHeaderHeight(0);
}
private void setHeaderHeight(final int height) {
if (height <= 1) {
mHeaderView.setVisibility(View.GONE);
} else {
mHeaderView.setVisibility(View.VISIBLE);
}
// Extends refresh bar
LayoutParams lp = (LayoutParams) mHeaderContainer.getLayoutParams();
if (lp == null) {
lp = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
}
lp.height = height;
mHeaderContainer.setLayoutParams(lp);
// Refresh bar shows up from bottom to top
LinearLayout.LayoutParams headerLp = (LinearLayout.LayoutParams) mHeaderView
.getLayoutParams();
if (headerLp == null) {
headerLp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
}
headerLp.topMargin = -mHeaderHeight + height;
mHeaderView.setLayoutParams(headerLp);
if (!mIsRefreshing) {
// If scroll reaches the trigger line, start refreshing
if (height > mHeaderHeight && !mArrowUp) {
mArrow.startAnimation(AnimationUtils.loadAnimation(
getContext(), R.anim.rotate));
mText.setText("Release to update");
rotateArrow();
mArrowUp = true;
} else if (height < mHeaderHeight && mArrowUp) {
mArrow.startAnimation(AnimationUtils.loadAnimation(
getContext(), R.anim.rotate));
mText.setText("Pull down to update");
rotateArrow();
mArrowUp = false;
}else {
if (isScrool == true) {
} else {
isScrool = true;
addHeaderView(vHeader);
// Animation anim = AnimationUtils.loadAnimation(
// getContext(), R.anim.bounce_animation);
// startAnimation(anim);
smoothScrollToPosition(getChildAt(0).getTop());
// bottom_layout.setVisibility(View.VISIBLE);
}
}
}
}
private void rotateArrow() {
Drawable drawable = mArrow.getDrawable();
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.save();
canvas.rotate(180.0f, canvas.getWidth() / 2.0f,
canvas.getHeight() / 2.0f);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
canvas.restore();
mArrow.setImageBitmap(bitmap);
}
private void startRefreshing() {
mArrow.setVisibility(View.INVISIBLE);
mProgress.setVisibility(View.VISIBLE);
mText.setText("Loading...");
mIsRefreshing = true;
if (mListener != null) {
mListener.onRefresh(this);
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(final Message msg) {
super.handleMessage(msg);
int limit = 0;
switch (msg.what) {
case REFRESH:
limit = mHeaderHeight;
break;
case NORMAL:
limit = 0;
break;
}
// Elastic scrolling
if (msg.arg1 >= limit) {
setHeaderHeight(msg.arg1);
int displacement = (msg.arg1 - limit) / 10;
if (displacement == 0) {
mHandler.sendMessage(mHandler.obtainMessage(msg.what,
msg.arg1 - 1, 0));
} else {
mHandler.sendMessage(mHandler.obtainMessage(msg.what,
msg.arg1 - displacement, 0));
}
}
}
};
public interface OnRefreshListener {
public void onRefresh(RefreshableListView listView);
}
public static interface ListViewObserver {
public void onScroll(float deltaY);
}
}
here in method dispatchTouchEvent(final MotionEvent ev) i have make one condition
if (isScrool == true) {
} else {
isScrool = true;
addHeaderView(vHeader);
// Animation anim =
// AnimationUtils.loadAnimation(
// getContext(), R.anim.bounce_animation);
// startAnimation(anim);
smoothScrollToPosition(getChildAt(0).getTop());
// bottom_layout.setVisibility(View.VISIBLE);
}
here addHeaderView(vHeader);
adds header but my listview scroll down to last item can anyone could tell me what's happening here?
Try to call listView.setSelectionAfterHeaderView();. This will scroll ListView to top.

Limit the touch event of the SlidingPaneLayout to the very left edge of the screen

Is it possibble to Limit the touch event of the SlidingPaneLayout to the very left edge of the screen link happens in the DrawerLayout?
Yes, but you want to create your own implementation of SlidingPaneLayout and override onTouchEvent(MotionEvent ev) method, like this
public class SlidingPaneLayoutExtended extends SlidingPaneLayout {
public static final int DEFAULT_DRAGGING_START_X = -1;
public static final int SLIDE_FROM_LEFT_EDGE = 0;
private int startDraggingX = DEFAULT_DRAGGING_START_X;
public SlidingPaneLayoutExtended(Context context, AttributeSet attrs) {
super(context, attrs);
}
public int getStartDraggingX() {
return startDraggingX;
}
public void setStartDraggingX(int startX) {
this.startDraggingX = startX;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (startDraggingX > DEFAULT_DRAGGING_START_X) {
if ((startDraggingX == SLIDE_FROM_LEFT_EDGE && ev.getAction() == )
|| ev.getX() <= DEFAULT_DRAGGING_START_X) {
return super.onTouchEvent(ev);
} else {
return false;
}
}
return super.onTouchEvent(ev);
}
}

Categories

Resources