MotionEvent.obtain(...); not working as on screen tapper - java

This is a continuation of my first topic here, about how to use code to mimic an on screen touch.
I wanted to incorporate this function to a floating, onscreen, chat-head (like what facebook did). So basically, when I tap the chat-head this service will mimic taps a certain amounts of times and at a certain rates. (Which are predefined somewhere else.) It will also mimic the tap at a certain spot x, y. (which are also predefined.) I want the service to tap whatever is behind (on the screen).
Here is my full code but it doesn't work and it doesn't show any errors.
It is a bit long and lengthy, if you don't have much time, then just skip to the runnable section. I am pretty confident there isn't any errors before the runnable section.
public class TapService extends Service{
private WindowManager windowManager;
private ImageView chatHead;
boolean mHasDoubleClicked = false;
long lastPressTime;
private Boolean _enable = true;
int x = 0;
int y = 0;
int tapTimes;
long delayInterval;
#Override
public IBinder onBind(Intent intent) {
// Not Used
return null;
}
#Override
public void onCreate() {
super.onCreate();
//////////////Chathead Core Section
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setImageResource(R.drawable.floating2);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
windowManager.addView(chatHead, params);
//////////Chathead Core Section
getTapInformation();
try {
chatHead.setOnTouchListener(new View.OnTouchListener() {
private WindowManager.LayoutParams paramsF = params;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
#Override public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Get current time in nano seconds.
long pressTime = System.currentTimeMillis();
// If double click...
if (pressTime - lastPressTime <= 300) {
// Do something else here
mHasDoubleClicked = true;
}
else { // If not double click....
mHasDoubleClicked = false;
}
lastPressTime = pressTime;
initialX = paramsF.x;
initialY = paramsF.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
x = paramsF.x;
y = paramsF.y;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
paramsF.x = initialX + (int) (event.getRawX() - initialTouchX);
paramsF.y = initialY + (int) (event.getRawY() - initialTouchY);
x = paramsF.x;
y = paramsF.y;
windowManager.updateViewLayout(chatHead, paramsF);
break;
}
return false;
}
});
} catch (Exception e) {
// TODO: handle exception
}
chatHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
_enable = false;
handler.post(runnable);
// Intent intent = new Intent(getApplicationContext(), MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
// getApplicationContext().startActivity(intent);
}
});
}
private Handler handler = new Handler();
private final Runnable runnable = new Runnable() {
#Override
public void run() {
long downTime;
long eventTime;
Log.v("Screen Tapper", "Start Tapping");
for(int i = 0; i <tapTimes; i++) {
downTime = eventTime = SystemClock.uptimeMillis();
MotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, x, y, 0);
chatHead.onTouchEvent(event);
Log.v("Screen Tapper", "touchDown ----- "+x+","+y);
handler.postDelayed(runnable, 10);
downTime = eventTime = SystemClock.uptimeMillis();
MotionEvent event2 = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, x, y, 0);
chatHead.onTouchEvent(event2);
Log.v("Screen Tapper", "touchUp ----- "+x+","+y);
handler.postDelayed(runnable, delayInterval);
}
}
};
private void getTapInformation() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
tapTimes = prefs.getInt("TAP_TIMES", 1);
delayInterval = prefs.getLong("Rate", 1);
Log.v("Screen Tapper", "Get Information");
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatHead != null) windowManager.removeView(chatHead);
}
}
I don't see anything wrong with my code but I have a feeling that the chatHead.onTouchEvent(...); is not correct
Any help is appreciated.
Thanks in advance

I beleive you need to run touch events on the UI thread for them to work, try this out
view.post(new Runnable() {
#Override
public void run() {
onTouchEvent(event);
}
});

Related

How to Track all gestures on ENTIRE android screen?

How do I track all gestures on an entire application screen. I was struggling with adding a gesture detector to the entire screen of my application. I am using gesturedetector compat to get gestures from the layout however when I tap or double tap the button and edit text gesturedetector does not detect the gesture on the view. Is it possible to have all tap,swipes,gestures on the ENTIRE screen as opposed to only the layout. If there is a better solution to tracking all touches,swipes,taps please let me know I have struggling with this for weeks.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private GestureDetectorCompat mGestureDetector;
private TextView touchCheckText;
private TextView singleTapText;
private TextView doubleTapText;
private static final String TAG = "Gesture ";
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction()!=KeyEvent.ACTION_DOWN)
Log.i("key pressed", String.valueOf(event.getKeyCode()));
return super.dispatchKeyEvent(event);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGestureDetector = new GestureDetectorCompat(this,new GestureListener());
touchCheckText = (TextView) findViewById(R.id.touchCheckTextView);
scrollText = (TextView) findViewById(R.id.scrollTextView);
singleTapText = (TextView) findViewById(R.id.singleTapTextView);
doubleTapText = (TextView) findViewById(R.id.doubleTapTextView);
}
private class GestureListener extends GestureDetector.SimpleOnGestureListener{
#Override
public boolean onDoubleTap(MotionEvent e) {
int x = (int) e.getX();
int y = (int) e.getY();
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
Log.e(TAG, "in on onDoubleTap Event");
doubleTapText.setBackgroundColor(Color.GREEN);
return super.onDoubleTap(e);
}
#Override
public boolean onDown(MotionEvent e) {
touchCheckText.setText("TOUCHING!");
return super.onDown(e);
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
int x = (int) e.getX();
int y = (int) e.getY();
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
singleTapText.setBackgroundColor(Color.GREEN);
Log.e(TAG, "Single Tap "+ts+" x:"+x+" y:"+y);
singleTapText.postDelayed(new Runnable() {
#Override
public void run() {
// change color in here
singleTapText.setBackgroundColor(Color.TRANSPARENT);
}
}, 100);
return super.onSingleTapConfirmed(e);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
switch ( event.getAction() ) {
case MotionEvent.ACTION_UP:
Log.e("onTouch","Released");
doubleTapText.setBackgroundColor(Color.TRANSPARENT);
touchCheckText.setText("No Longer Touching");
break;
}
return super.onTouchEvent(event);
}
}

Android Studio - How to use implement swipe gesture in android game

I was working on a game on Android studio where user touch drives tiles to combine. To do this, I have used a GridLayout separated into rows and columns. The value is displayed with imageview and all gridlayout cells are linked to a separate cell class which includes imageview ID's. I implemented a listener on each image view to detect when a swiping motion occured. The code for initalizing the board and listeners is below:
for(int i = 0; i<noOfBlocks; i++) {
for (int j = 0; j < noOfBlocks; j++) {
ImageView imageView = new ImageView(this);
imageView.setId(iDcnt);
imageView.setLayoutParams(new ViewGroup.LayoutParams(widthOfBlock, widthOfBlock));
imageView.setMaxHeight(widthOfBlock);
imageView.setMaxWidth(widthOfBlock);
int randomNum = (int) Math.floor(random.nextDouble() * gamepiece.length);
imageView.setImageResource(gamepiece[randomNum]);
Cell c = new Cell(i + 1, j+1, randomNum, imageView.getId());
imageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
SquarePlay s = null;
try {
s = new SquarePlay();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
s.onSwipeEvent(event);
return false;
}
});
gameBoard.addView(imageView);
iDcnt++;
}
The OnTouch events are handled in a separate class in the method which is shown below:
float x1, x2, y1, y2, dx, dy;
public void onSwipeEvent(MotionEvent event){
switch(event.getAction()) {
case(MotionEvent.ACTION_DOWN):
x1 = event.getX();
y1 = event.getY();
break;
case(MotionEvent.ACTION_UP): {
x2 = event.getX();
y2 = event.getY();
dx = x2-x1;
dy = y2-y1;
if(Math.abs(dx) > Math.abs(dy)) {
if(dx>0)
onSwipeRight();
else
onSwipeLeft();
} else {
if(dy>0)
onSwipeDown();
else
onSwipeUp();
}
}
}
}
private void onSwipeLeft() {
System.exit(0);
}
private void onSwipeRight() {
System.exit(0);
}
private void onSwipeUp() {
System.exit(0);
}
private void onSwipeDown() {
System.exit(0);
}
NOTE:System.exit is just there to test if this works.
The App loads but does not produce a response from the swipe events, Does anyone have any suggestions on how to resolve this issue?
Thank you :)
To use swipe You can create your class inside the activity class as follow##
declare the class name inside the activity class
SwipeListener swipeListener;
inside the activity class write this code to handle the swipe##
private class SwipeListener implements View.OnTouchListener {
//create gesture detector variable
GestureDetector gestureDetector;
//create constructor
SwipeListener(View view){
int threshold = 100;
int velocity_threshold = 100;
GestureDetector.SimpleOnGestureListener listener =
new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onDown(MotionEvent e) {
return super.onDown(e);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
//get x and y difference
float xDiff = e2.getX() - e1.getX();
float yDiff = e2.getY() - e1.getY();
try {
if(Math.abs(xDiff)>Math.abs(yDiff)){
if(Math.abs(xDiff)>threshold &&
Math.abs(velocityX)> velocity_threshold){
if(xDiff > 0){
//swipe right
Intent intent = new Intent(TopUpBalance.this, HomePage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}else{
//swipe left
}
return true;
}//you can handle swipe down and above here as well, the same way above
}
}catch (Exception e){
e.printStackTrace();
}
return false;
}
};
//init gesture
gestureDetector = new GestureDetector(listener);
view.setOnTouchListener(this);
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return gestureDetector.onTouchEvent(motionEvent);
}
}
Declare your SwipeListener onCreate method as follow##
linearLayout = findViewById(R.id.layoutID);
//swipe
swipeListener = new SwipeListener(linearLayout);

How to have static dialog fragment method to use throughout app in Android?

I have created a DialogFragment class that I need to show from within a onDragListener. I tried a regular AlertDialog but couldn't get the activity context to be static. I tried adding this to my onDragListener class and to my CustomLayoutClass but it says that getSupportFragmentManager() cannot be referenced from a static method or that it cannot be resolved.
public static void showScoopDialog() {
FragmentManager fm = getSupportFragmentManager();
ScoopSizeDialog editNameDialogFragment = ScoopSizeDialog.newInstance("Some Title");
editNameDialogFragment.show(fm, "fragment_edit_name");
}
This is my custom onDragListener class. I need to show a dialog with edittext when the user drops an image:
public class ChoiceDragListener implements View.OnDragListener {
boolean DEBUG = true;
Context context;
public String TAG = "Drag Layout:";
public ChoiceDragListener(Context context) {
this.context = context;
}
#Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
if(DEBUG) Log.v("here","drag started");
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DRAG_LOCATION:
int mCurX = (int) event.getX();
int mCurY = (int) event.getY();
if (DEBUG) Log.v("Cur(X, Y) : " ,"here ::" + mCurX + ", " + mCurY );
break;
case DragEvent.ACTION_DRAG_EXITED:
if (DEBUG)
Log.v("here","drag exits");
break;
case DragEvent.ACTION_DROP:
//handle the dragged view being dropped over a drop view
View view = (View) event.getLocalState();
ClipData cd = event.getClipData();
ClipData.Item item = cd.getItemAt(0);
String resp = item.coerceToText(context).toString();
//view dragged item is being dropped on
ImageView dropTarget = (ImageView) v;
//view being dragged and dropped
ImageView dropped = (ImageView) view;
dropped.setEnabled(false);
//if an item has already been dropped here, there will be a tag
Object tag = dropTarget.getTag();
CreateProd.nsList.add(dropped.getTag().toString());
Log.d(TAG, dropped.getTag().toString() + "added to list");
//if there is already an item here, set it back visible in its original place
if (tag != null) {
//the tag is the view id already dropped here
int existingID = (Integer)tag;
//set the original view visible again
((Activity) context).findViewById(existingID).setVisibility(View.VISIBLE);
}
break;
case DragEvent.ACTION_DRAG_ENDED:
if (DEBUG) Log.i("drag event", "ended::" + ChoiceTouchListener.offsetX + "," + ChoiceTouchListener.offsetY);
/**
* returning false so that goes to parentView onDrag function
*/
return false;
//break;
default:
break;
}
return true;
}
}
And this is my custom layout:
public class DragLayout extends RelativeLayout {
boolean DEBUG = true;
AnimationDrawable blenderAnim;
Handler handlerAnim2;
Context context;
private int dimensionInPixel = 200;
int screenWidth,screenHeight;
static float up_x=0,up_y=0;
boolean mIsScrolling = false;
public DragLayout(Context context) {
super(context);
// TODO Auto-generated constructor stub
this.context = context;
//not to include in main program
getDimensionsofScreen();
setLayout();
setViews();
}
private void setLayout() {
// set according to parent layout (not according to current layout)
RelativeLayout.LayoutParams rLp = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
rLp.topMargin = 2 * (screenHeight / 25); // calculating 1/10 of 4/5
// screen
this.setLayoutParams(rLp);
}
void setViews() {
ImageView img2 = new ImageView(context);
int dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());
RelativeLayout.LayoutParams rLp = new RelativeLayout.LayoutParams(
(screenWidth / 5), (screenHeight / 5));
rLp.topMargin = (screenHeight / 10);
rLp.leftMargin = (4*screenWidth / 10);
rLp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
img2.setLayoutParams(rLp);
img2.getLayoutParams().height = dimensionInDp;
img2.getLayoutParams().width = dimensionInDp;
img2.setImageDrawable(getResources().getDrawable(R.drawable.blender_anim));
img2.setOnDragListener(new ChoiceDragListener(context));
this.addView(img2);
blenderAnim = (AnimationDrawable)img2.getDrawable();
blenderAnim.setOneShot(true);
blenderAnim.stop();
}
public ArrayList<Integer> getDimensionsofScreen() {
//metrics that holds the value of height and width
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();;
ArrayList<Integer> vals = new ArrayList<Integer>();
vals.add(displayMetrics.widthPixels);
vals.add(displayMetrics.heightPixels);
screenHeight = displayMetrics.heightPixels;
screenWidth = displayMetrics.widthPixels;
return vals;
}
#SuppressLint("NewApi")
#Override
public boolean onDragEvent(DragEvent event) {
int mCurX = (int) event.getX();
int mCurY = (int) event.getY();
if (event.getAction() == DragEvent.ACTION_DRAG_STARTED || event.getAction() == DragEvent.ACTION_DRAG_ENTERED) {
if (blenderAnim.isRunning()) {
blenderAnim.stop();
} else {
blenderAnim.run();
handlerAnim2 = new Handler();
handlerAnim2.postDelayed(
new Runnable() {
#Override
public void run() {
blenderAnim.stop();
}},
getAnimationDuration(blenderAnim));
}
}
if (event.getAction() == DragEvent.ACTION_DROP || event.getAction() == DragEvent.ACTION_DRAG_EXITED) {
if (blenderAnim.isRunning()) {
blenderAnim.stop();
} else {
blenderAnim.run();
handlerAnim2 = new Handler();
handlerAnim2.postDelayed(
new Runnable(){
#Override
public void run() {
blenderAnim.stop();
}},
getAnimationDuration(blenderAnim));
}
Log.v("here", "it is :: " + mCurX + ", " + mCurY);
View view1 = (View) event.getLocalState();
view1.setVisibility(View.VISIBLE);
ObjectAnimator animationx = ObjectAnimator.ofFloat(view1,"translationX", mCurX - ChoiceTouchListener.offsetX-(screenWidth / 10),0.0f);
ObjectAnimator animationy = ObjectAnimator.ofFloat(view1, "translationY", mCurY - ChoiceTouchListener.offsetY - (screenHeight / 10), 0.0f);
AnimatorSet animSet = new AnimatorSet();
animSet.setDuration(500);
animSet.playTogether(animationx,animationy);
animSet.start();
}
if (event.getAction() == DragEvent.ACTION_DROP || event.getAction() == DragEvent.ACTION_DRAG_ENDED){
if (blenderAnim.isRunning()) {
blenderAnim.stop();
}
}
return true;
}
private int getAnimationDuration(AnimationDrawable src) {
int dur = 0;
for (int i = 0; i<src.getNumberOfFrames(); i++) {
dur += src.getDuration(i);
}
return dur;
}
private void showScoopDialog() {
FragmentManager fm = getSupportFragmentManager();
ScoopSizeDialog editNameDialogFragment = ScoopSizeDialog.newInstance("Some Title");
editNameDialogFragment.show(fm, "fragment_edit_name");
}
}

App crashing when using SharedPreferences to carry over final score

My android app is crashing when using SharedPreferences to try and carry the final score over from when the game ends. The app crashes inside the onTouchEvent at the line.
SharedPreferences.Editor editor = mySharedPreferences.edit();
The idea is when the game ends it final score that is within the SVGameView to carry over into the SVGameOver class and display there. If anyone could give some advice that would be great!
SVGameView:
public class SVGameView extends SurfaceView implements Runnable {
private SurfaceHolder holder;
Thread thread = null;
volatile boolean running = false;
static final long FPS = 30;
private Sprite sprite;
private long lastClick;
private Bitmap ball, gameOver;
//private int x = 200, y = 200;
private int scorePosX = 100;
private int scorePosY = 100;
private int countScore = 0;
private int life = 1;
SharedPreferences mySharedPreferences;
public SVGameView(Context context) {
super(context);
thread = new Thread(this);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
running = false;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
running = true;
thread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball2);
gameOver = BitmapFactory.decodeResource(getResources(),R.drawable.endscreen);
sprite = new Sprite(this, ball);
context.getSharedPreferences("myPrefsFile",Context.MODE_PRIVATE);
}
#Override
public void run() {
long ticksPS = 1000 / FPS;
long startTime;
long sleepTime;
while (running) {
Canvas c = null;
startTime = System.currentTimeMillis();
try {
c = getHolder().lockCanvas();
synchronized (getHolder()) {
update();
onDraw(c);
}
} finally {
if (c != null) {
getHolder().unlockCanvasAndPost(c);
}
}
sleepTime = ticksPS-(System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
thread.sleep(sleepTime);
else
thread.sleep(10);
} catch (Exception e) {}
}
}
private void update(){
sprite.update();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
Paint paint = new Paint();
canvas.drawPaint(paint);
paint.setColor(Color.WHITE);
paint.setTextSize(48);
canvas.drawText("Score: " + countScore, scorePosX, scorePosY, paint);
canvas.drawText("Lives: " + life, 500, 100, paint);
sprite.onDraw(canvas);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(System.currentTimeMillis()-lastClick > 300){
lastClick = System.currentTimeMillis();
}
synchronized (getHolder()){
if(sprite.isHit(event.getX(), event.getY())){
countScore += 1;
sprite.increase();
}else{
life --;
}
}
if(life == 0) {
getContext().startActivity(new Intent(getContext(), SVGameOver.class));
//Intent intent;
//intent = new Intent(getContext(), SVGameView.class);
//intent.putExtra("scoreOutput", countScore);
//Crashes Here
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("cScore", String.valueOf(countScore));
}
return super.onTouchEvent(event);
}
}
SVGameOver Class:
public class SVGameOver extends Activity implements View.OnClickListener{
Button btnBack;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(this);
SharedPreferences mySharedPreferences = getSharedPreferences("myPrefsFile", 0);
String theScore = mySharedPreferences.getString("cScore","");
TextView textView = (TextView)findViewById(R.id.scoreOutput);
textView.setText(theScore);
//intent = getIntent();
//String uir = intent.getStringExtra("scoreOutput");
}
#Override
public void onClick(View v) {
}
}
XML Layout:
https://gyazo.com/8e49d02c66dde7ff0e7f09a4fa9eacd2
You're missing:
mySharedPreferences = context.getSharedPreferences("myPrefsFile", Context.MODE_PRIVATE);
in your SVGameView, so mySharedPreferences always null.
You missed assigning SharedPreferencesobject to your reference mySharedPreferences in SVGameView(Context context) -
context.getSharedPreferences("myPrefsFile",Context.MODE_PRIVATE);
Change it to
mySharedPreferences = context.getSharedPreferences("myPrefsFile",Context.MODE_PRIVATE);
You are not initializing the SharedPreference object right.
Use this library, which simplifies the use of SharedPreferences and will make life simpler for you.
Android-SharedPreferences-Helper simplifies usage of the default Android SharedPreferences Class. The developer can do in a few lines
of code which otherwise would have required several. Simple to
understand as compared to the default class and easy to use.

OnTouchListener is not responding

I am creating a little popup like the facebook's chathead.
The bubble fires up and appears but the ontouchlistener is not responding on it
the ontouch events does what It is supposed to do when I tested it but when I integrated it, it's not firing
Below is the code I used to create the layout of the bubble and ontouchlistener
public HeadLayer(Context context) {
super(context);
mContext = context;
mFrameLayout = new FrameLayout(mContext);
addToWindowManager();
}
private void addToWindowManager() {
final WindowManager.LayoutParams myParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
PixelFormat.TRANSLUCENT);
myParams.gravity = Gravity.LEFT;
mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
mWindowManager.addView(mFrameLayout, myParams);
try{
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Here is the place where you can inject whatever layout you want.
View view = layoutInflater.inflate(R.layout.head, mFrameLayout);
//for moving the picture on touch and slide
headIcon = (ImageView)view.findViewById(R.id.head_icon);
headIcon.setOnTouchListener(new View.OnTouchListener() {
WindowManager.LayoutParams paramsT = myParams;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
private long touchStartTime = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
touchStartTime = System.currentTimeMillis();
initialX = myParams.x;
initialY = myParams.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
myParams.x = initialX + (int) (event.getRawX() - initialTouchX);
myParams.y = initialY + (int) (event.getRawY() - initialTouchY);
mWindowManager.updateViewLayout(v, myParams);
break;
}
return false;
}
});
} catch (Exception e){
e.printStackTrace();
}
}
Hi You have added Framelayout first then get its child Using LayoutInflator. You have to first initialize all view and listeners then added it to window manager.
Check This Link : http://www.piwai.info/chatheads-basics/
That's it..

Categories