Error on Long Press Android Event - android

I try to show a toast when user long press android screen....but nothing showing.Why?Simple touch shows toast " touch " work fine! Where is the error?
public class MainActivity extends Activity {
Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Runnable mLongPressed = new Runnable() {
public void run() {
Toast.makeText(getBaseContext(),
"Long press",
Toast.LENGTH_LONG).show();
}
};
#Override
public boolean onTouchEvent(MotionEvent event){
if(event.getAction() == MotionEvent.ACTION_DOWN)
Toast.makeText(getBaseContext(),
" touch ",
Toast.LENGTH_LONG).show();
handler.postDelayed(mLongPressed, 1000);
if((event.getAction() == MotionEvent.ACTION_MOVE)||(event.getAction() == MotionEvent.ACTION_UP))
handler.removeCallbacks(mLongPressed);
return super.onTouchEvent(event);
}

You should use GestureDetector to determine the long press, like the following:
final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
public void onLongPress(MotionEvent e) {
Toast.makeText(getBaseContext(), "Long press", Toast.LENGTH_LONG).show();
}
});
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
};

Snippet:
public class MainActivity extends Activity implements OnLongClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View yourView = (View) findViewById(R.id.longclickview);
yourView.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View v) {
Toast.makeText(getBaseContext(),
"Long press",
Toast.LENGTH_LONG).show();
return false;
}

Related

View.OnTouchListener stops responding after thread start

Why does the View.OntouchListener stops working after thread.start?
Here's my code:
public class MultiviewActivity extends Activity implements Runnable {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
c = getBaseContext();
handler = new myHandler();
final GestureDetector detector = new GestureDetector(c, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onDoubleTap(MotionEvent e) {
return true;
}
#Override
public boolean onDown(MotionEvent e) {
Log.i("multiView", "Touch id=" + viewid);
return true;
}
public boolean onSingleTapConfirmed(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
}
});
View.OnTouchListener touchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
viewid = v.getId();
return detector.onTouchEvent(event);
}
};
LinearLayout lay = findViewById(R.id.l1);
lay.setOnTouchListener(touchListener);
//timer
Runnable timerrunnable = new Runnable() {
#Override
public void run() {
if (!bisruning) {
thread = new Thread(MultiviewActivity.this);
thread.start();
}
timerhandler.postDelayed(this, 1000);
}
};
timerhandler.postDelayed(timerrunnable, 5000);
}
#Override
public void run() {
bisruning = true;
msg = handler.obtainMessage();
Log.i("multiView", "Running thread");
//thread task goes here...
msg.arg1 = 0;
msg.arg2 = 1;
handler.sendMessage(msg);
}
class myHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.arg1) {
case 0:
if (msg.arg2 == 1)
fillLayout();
bisruning = false;
break;
}
}
}
}
As soon as my timer ticks in (after 5s), the view stops responding to screen taps...
I know that the View is responding to taps before the thread starts because I've logged the OnDown event.
What am I doing wrong?
Thank you for your help.
Regards

Android gesture is not working in activity

i have some images in the activity i need to implement gesture when i swife images so bellow i have posted my code (there is full code but the gesture is not working)
As bellow is my code (activity class ), implemented gesture
i have created gesture in my code but it is not working,
it is not calling onTouch event also, when i click its not printing any logs
how can i solve this problem.
at the last there is onFling method is there
public class PageView extends AppCompatActivity implements ReadOutTextAnimation.ReadingPageCompleted, OnGestureListener {
public static final String TAG = PageView.class.getName();
private Button mPlayBtn;
private Button mBtnNext;
private Button mBackBtn;
private ImageView mBgImage;
private Integer mPageNumber;
private String mMainFolder;
private Handler handler = new Handler();
private Runnable mTimerCallback;
private boolean mIsPaused;
private GestureDetector gestureDetector;
private boolean isoneclick;
private LinearLayout mLenearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
gestureDetector = new GestureDetector(this, this);
// mLenearLayout = (LinearLayout)findViewById(R.id.clickhide);
// mLenearLayout.setVisibility(View.INVISIBLE);
isoneclick = true;
if (AppManager.getInstance().getNeedsBGMusic())
SoundManager.getInstance().resumeBackgroundMusic();
mPageNumber = 1;
mMainFolder = String.valueOf(BaseApplication.getInstance().getAppContext().getDir("Books", Context.MODE_PRIVATE));
mMainFolder += "/Downloads" + AppManager.getInstance().getCurrentBook().getBookId().toString();
mTimerCallback = new Runnable() {
#Override
public void run() { loadNextPage(); }
};
ReadOutTextAnimation.getInstance().setListner(this);
mBgImage = findViewById(R.id.page_view_bgimage);
mBgImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onSlideViewButtonClick(v);
//loadNextPage();
}
});
//Next Button Action
mBtnNext = findViewById(R.id.page_view_nextbtn);
mBtnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadNextPage();
}
});
//Back Button Action
mBackBtn = findViewById(R.id.page_view_backbtn);
mBackBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadPreviousPage();
}
});
//Play & Pause Button Action
mPlayBtn = findViewById(R.id.page_view_palybtn);
mPlayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mIsPaused){
resumeApp();
} else {
pauseApp();
}
}
});
loadPageDetails();
enableBtn();
Button mDoneBtn = findViewById(R.id.page_view_done);
mDoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
}
#Override
protected void onPause() {
super.onPause();
pauseApp();
}
private void enableBtn(){
if(mPageNumber > 1) {
mBackBtn.setEnabled(true);
mBtnNext.setEnabled(true);
mBackBtn.setAlpha(.9f);
}else {
mBackBtn.setAlpha(.5f);
mBtnNext.setEnabled(true);
}
}
private void loadPageDetails(){
ReadOutTextAnimation.getInstance().stopReadOut();
PageDetailProperties mCurrentPage = AppManager.getInstance().getCurrentBook().getPageDetailsForNumber(mPageNumber);
if (mCurrentPage.getPageAudioDurationJSON() == null)
{
loadNextPage();
return;
}
File imgFile = new File(mMainFolder,ContentfulConstants.PAGE_IMAGE+ mPageNumber.toString() +".png");
if (imgFile.exists()){
Bitmap bookImage = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
mBgImage.setImageBitmap(bookImage);
}
File soundFile = new File(mMainFolder,ContentfulConstants.PAGE_AUDIO+mPageNumber.toString()+".mp3");
if (soundFile.exists()){
SoundManager.getInstance().playPageAudio(soundFile.getPath());
}
ReadOutTextAnimation.getInstance().startReadOut(mPageNumber);
mIsPaused = false;
mPlayBtn.setBackgroundResource(R.drawable.pause);
}
private void loadNextPage(){
handler.removeCallbacks(mTimerCallback);
mPageNumber++;
if (mPageNumber > AppManager.getInstance().getCurrentBook().getPageDetail().size()){
mPageNumber = AppManager.getInstance().getCurrentBook().getPageDetail().size();
ReadOutTextAnimation.getInstance().setListner(null);
ReadOutTextAnimation.getInstance().stopReadOut();
SoundManager.getInstance().stopALL();
Intent intent = new Intent(this , BookCompleteView.class);
this.finish();
startActivity(intent);
} else {
loadPageDetails();
enableBtn();
}
}
private void loadPreviousPage(){
mPageNumber--;
handler.removeCallbacks(mTimerCallback);
if (mPageNumber < 1){
mPageNumber = 1;
} else {
loadPageDetails();
}
enableBtn();
}
#Override
public void readingPageCompleted() {
handler.postDelayed(mTimerCallback, 700);
}
#Override
public void onBackPressed() {
ReadOutTextAnimation.getInstance().setListner(null);
handler.removeCallbacks(mTimerCallback);
ReadOutTextAnimation.getInstance().stopReadOut();
SoundManager.getInstance().stopALL();
super.onBackPressed();
}
#Override
public boolean onDown(MotionEvent motionEvent) {
return false;
}
#Override
public void onShowPress(MotionEvent motionEvent) {
}
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
return false;
}
#Override
public void onLongPress(MotionEvent motionEvent) {
}
#Override
public boolean onTouchEvent(MotionEvent motionEvent) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "touch" , Toast.LENGTH_SHORT).show();
gestureDetector.onTouchEvent(motionEvent);
return false;
}
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
System.out.println("Gesture event touch ");
if (motionEvent.getX() - motionEvent1.getX() > 50) {
loadNextPage();
return true;
}
if (motionEvent1.getX() - motionEvent.getX() > 50) {
loadPreviousPage();
return true;
}
return false;
}
}
If I understood you correctly. You have to set touch listener for your image view, instead of activity.
mBgImage.setOnTouchListener(yourTouchListener);

Android ontouchlistener counter implementation

I have set ontouch listener to implement a counter for my imagebutton. But I can only detect button being touched and release. I am not sure how to implement incrementing as long as the button is pressed and how to stop it after it is released. Following is the code I have:
up.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) {
pressdown();
}
else if (event.getAction()==MotionEvent.ACTION_UP) {
pressrelease();
}
return true;
}
Ok. Here's a solution to my own question. It might help someone else.
use a Handler object because you have to implement a separate thread for incrementing/decrementing
public class MainActivity extends Activity{
private boolean autoIncrement = false;
private boolean autoDecrement = false;
private final long REPEAT_DELAY = 50;
private Handler repeatUpdateHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input);
class RepetitiveUpdater implements Runnable{
#Override
public void run() {
if (autoIncrement) {
increment();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
}
else if(autoDecrement){
decrement();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
}
}
}
up.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
increment();
}
});
up.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
autoIncrement = true;
repeatUpdateHandler.post(new RepetitiveUpdater());
return false;
}
});
up.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_UP && autoIncrement ){
autoIncrement = false;
}
return false;
}
});
public void increment(){
if (i<100) {
i++;
TextView no = (TextView)findViewById(R.id.no);
no.setText(String.valueOf(i));
}
}
}
Do the same for decrement.
Courtesy: Github, author: Jeffrey F. Cole

about used value on Progress Bar

I am developing game in android. I want to used to value progress of Progress Bar to do force shot a arrows .And this is my code :
public class TheArrows extends Activity {
ProgressBar myProgressBar;
private int myProgress=0;
private int t=0;
#Override public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
myProgressBar=(ProgressBar)findViewById(R.id.progressbar_Horizontal);
app.quabongchuyendong.QuaBongView quaBongView=(app.quabongchuyendong.QuaBongView) findViewById(R.id.qua_bong);
quaBongView.setOnTouchListener(new OnTouchListener() {
#Override public boolean onTouch(View view, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN){ t=1; }
if(event.getAction()==MotionEvent.ACTION_MOVE){ t=1; }
if(event.getAction()==MotionEvent.ACTION_UP){ t=0; }
return false;
}
});
new Thread(myThread).start();
}
private Runnable myThread = new Runnable(){
#Override public void run() {
// TODO Auto-generated method stub
while (myProgress<100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(100);
} catch(Throwable t){ }
}
}
Handler myHandle = new Handler(){
#Override public void handleMessage(Message msg) {
if(t==1) myProgress++;
myProgressBar.setProgress(myProgress);
}
};
};
public int progressValue(){
return myProgress;
}
}
Although I have myProgress++; why myProgress in progressValue() doesn't change? Please help me.
new Thread(myThread).start();
Should be in OnTouch befaore return statement;
Try This :
#Override public boolean onTouch(View view, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN){ t=1; }
else if(event.getAction()==MotionEvent.ACTION_MOVE){ t=1; }
else if(event.getAction()==MotionEvent.ACTION_UP){ t=0; }
new Thread(myThread).start();
return false;
}
});
and Remove if(t==1) condition in handler Handler
myHandle = new Handler(){
#Override public void handleMessage(Message msg) {
myProgress++;
myProgressBar.setProgress(myProgress);
}
};
};

Thread -while loop- [Android]

So in my further attempts to implement a while loop in android I have come up with the code below :
private boolean connected = false;
private Thread loop = new Thread() {
public void run() {
Looper.prepare();
while (connected) {
do_Something();
}
Looper.loop();
}
};
onCreate() {
//.....
ok = (Button) findViewById(R.id.button1);
ok.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (connected) {
try {
loop.start();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), "Exception caught", Toast.LENGTH_LONG).show();
}
}
return true;
}
});
stop = (Button)findViewById(R.id.button2);
stop.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//disconnects current connection
connected = false;
}
return true;
}
});
}
That is, I am trying to on the touch of the first button have my UI thread switch to the thread that will do_something over and over again until the touch of the second button, in which case the boolean var k will switch off and completely stop the newly created thread from the button press of the first button. I have google'd "threads/handlers/android while loops" but to no avail. Any help towards what I am trying to do would be much appreciated
Simply put, how do I kill the thread that was created via pressing the second button?
Did you tried AsyncTask ? What you can do...start a new AsyncTask on firstButton click and cancel it on secondButton click.
//define global variable
private DoSomething doSomething;
//register firstButton onClickListener
firstButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//start your asynctask
if(doSomething == null || doSomething.isCancelled()){
doSomething = new DoSomething();
doSomething = doSomething.execute();
}
}
});
//register secondButton onClickListener
secondButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
doSomething.cancel();
}
});
//Inner AsyncTask class
class DoSomething extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
//doSomething();
while(true){
System.out.println(1);
if(isCancelled()){
break;
}
}
return null;
}
}
Note: This is pseudocode...might contain error...just want to give you overview. hope this help.

Categories

Resources