How can I check user interaction on android dialog? - android

Android activity has overridden method onUserInteraction.But how can I check the user interaction in the dialog?I want to develop some logic based on this.Please help
This code works (onUserInteraction)fine with Activity
public class MyBaseActivity extends Activity {
public static final long DISCONNECT_TIMEOUT = 300000; // 5 min = 5 * 60 * 1000 ms
private Handler disconnectHandler = new Handler(){
public void handleMessage(Message msg) {
}
};
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
}
};
public void resetDisconnectTimer(){
disconnectHandler.removeCallbacks(disconnectCallback);
disconnectHandler.postDelayed(disconnectCallback, DISCONNECT_TIMEOUT);
}
public void stopDisconnectTimer(){
disconnectHandler.removeCallbacks(disconnectCallback);
}
#Override
public void onUserInteraction(){
resetDisconnectTimer();
}
#Override
public void onResume() {
super.onResume();
resetDisconnectTimer();
}
#Override
public void onStop() {
super.onStop();
stopDisconnectTimer();
}
}
But how can I use 'onUserInteraction' method with Dialog ?
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
final Dialog dialog = new Dialog(MainActivity.this);
//setting custom layout to dialog
dialog.setContentView(R.layout.cusotm_dialog_layout);
dialog.setTitle("Custom Dialog");
//adding text dynamically
TextView txt = (TextView) dialog.findViewById(R.id.textView);
txt.setText("Put your dialog text here.");
ImageView image = (ImageView)dialog.findViewById(R.id.image);
image.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_dialog_info));
//adding button click event
Button dismissButton = (Button) dialog.findViewById(R.id.button);
dismissButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}

I have implemented onUserInteraction for DialogFragment. This has the same handling as Activity for onUserInteraction. The setUserInteractionEnabled method can also be implemented in an Activity subclass.
public abstract class BaseDialogFragment
extends DialogFragment
{
protected void onUserInteraction()
{
Activity activity = getActivity();
if(activity != null)
{
activity.onUserInteraction();
}
}
protected void setUserInteractionEnabled(Dialog dialog, boolean enabled)
{
if(!enabled)
{
dialog.getWindow().setCallback(dialog);
return;
}
dialog.getWindow().setCallback(new WindowCallbackWrapper(dialog)
{
#Override
public boolean dispatchKeyEvent(KeyEvent event)
{
onUserInteraction();
return super.dispatchKeyEvent(event);
}
#Override
public boolean dispatchKeyShortcutEvent(KeyEvent event)
{
onUserInteraction();
return super.dispatchKeyShortcutEvent(event);
}
#Override
public boolean dispatchTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
onUserInteraction();
}
return super.dispatchTouchEvent(event);
}
#Override
public boolean dispatchTrackballEvent(MotionEvent event)
{
onUserInteraction();
return super.dispatchTrackballEvent(event);
}
#Override
public boolean dispatchGenericMotionEvent(MotionEvent event)
{
onUserInteraction();
return super.dispatchGenericMotionEvent(event);
}
});
}
}
Call this in your onCreateDialog.
public class MyDialogFragment
extends BaseDialogFragment
{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Dialog dialog = new Dialog(getContext());
setUserInteractionEnabled(dialog, true);
return dialog;
}
}
Note: this will not call onUserInteraction from the dialog's soft keyboard. That should be handled from a TextWatcher that calls onUserInteraction in afterTextChanged.

Related

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);

In Android where to put the global method?

Below is my code to exit my app.
Since I have more than 1 activity, where should I put exitBy2Click() so it can be use for all activities?
I tried to create a new class called "Global", and public exitBy2Click(), but Toast.makeText(this,... not work.
Thanks.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
exitBy2Click();
}
return false;
}
private static Boolean isExit = false;
private void exitBy2Click() {
Timer tExit = null;
if (!isExit) {
isExit = true;
Toast.makeText(this, "click again to quit", Toast.LENGTH_SHORT).show();
tExit = new Timer();
tExit.schedule(new TimerTask() {
#Override
public void run() {
isExit = false;
}
}, 2000);
} else {
finish();
System.exit(0);
}
}
Checking your method, I think that best option would be Inheritance..
Note on example below that you can override onBackPressed() instead of onKeyDown()
public class BaseActivity extends Activity {
private static Boolean isExit = false;
#Override
public void onBackPressed() {
exitBy2Click();
}
public void exitBy2Click() {
Timer tExit = null;
if (!isExit) {
isExit = true;
Toast.makeText(this, "click again to quit", Toast.LENGTH_SHORT).show();
tExit = new Timer();
tExit.schedule(new TimerTask() {
#Override
public void run() {
isExit = false;
}
}, 2000);
} else {
finish();
System.exit(0);
}
}
}
Then, your "real" activities can extends that BaseActivity and this way, onKeyDown and exitBy2Click will be commom to all classes.
public class MainActivity extends BaseActivity {
#override
public void onCreate(Bundle savedInstance) {
}
}
public class SecundaryActivity extends BaseActivity {
#override
public void onCreate(Bundle savedInstance) {
}
}
//ETC
The best place to put this code is literally "nowhere".
Forcibly terminating an Android app is not recommended, and calling System.exit is definitely not something you should ever do in an Android app.

Restarting a CountDownTimer in a Dialog window after an OnTouchEvent in a fragment

I have a CountDownTimer that dismisses a dialog popup window. I would like for this timer to restart if the user touches the screen. Here is what I have so far,
public class dataCapture extends Fragment implements OnClickListener {
...
MotionEvent event;
View.OnTouchListener touchListener;
#Override
public void onCreate(Bundle savedDataEntryInstanceState) {
super.onCreate(savedDataEntryInstanceState);
setRetainInstance(true);
}
...
#Override
public View onCreateView
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnHelpFilexml:
openHelpDialog();
break;
...
}
private void openHelpDialog() {
Button btnCloseWindow;
final Dialog helpDialog;
TextView tvHelpDialogTitle, tvHelpDialogBody;
helpDialog = new Dialog(getActivity(), android.R.style.Theme_Translucent);
helpDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
helpDialog.setCancelable(true);
helpDialog.setContentView(R.layout.help_dialog);
tvHelpDialogTitle = (TextView) helpDialog.findViewById(R.id.tvHelpDialogTitle);
tvHelpDialogTitle.setText("DataCapture Help");
tvHelpDialogBody = (TextView) helpDialog.findViewById(R.id.tvHelpDialogBody);
tvHelpDialogBody.setText("Start of help text\n" +
"This is help text\n" +
"\n" +
"Here we go...\n" +
...
"This is the end.");
btnCloseWindow = (Button) helpDialog.findViewById(R.id.btnCloseWindow);
btnCloseWindow.setText("Close");
btnCloseWindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpDialog.dismiss();
}
});
CountDownTimer countDownTimer = new CountDownTimer(30000, 1000) {
// new countDownTimer(30000, 1000) {//makes popup go away after 30 secs
#Override
public void onTick(long millisUntilFinished) {//Do something every second...
}
#Override
public void onFinish() {//action at end of specified time
helpDialog.dismiss();
}
}.start();
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) {
countDownTimer.cancel();
countDownTimer.start();
}
return super.onTouchEvent(event);
}
helpDialog.show();
}
}
Any suggestions regarding how best to implement this function would be highly appreciated. Copious TIA.
UPDATE Got it. Solution below. Thanks.
public class dataCapture extends Fragment implements OnClickListener {
...
private static final int COUNTDOWN_TIME_MS = 30000;
Handler handlerHelpDialogTimer;
Runnable runnableHelpDialogDismissCountdown;
Dialog helpDialog;
private Dialog getHelpDialog() {
Button btnCloseWindow;
final Dialog helpDialog;
TextView tvHelpDialogTitle, tvHelpDialogBody;
helpDialog = new Dialog(getActivity(), android.R.style.Theme_Translucent);
helpDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
helpDialog.setCancelable(true);
helpDialog.setContentView(R.layout.help_dialog);
tvHelpDialogTitle = (TextView) helpDialog.findViewById(R.id.tvHelpDialogTitle);
tvHelpDialogTitle.setText("DataCapture Help");
tvHelpDialogBody.setText("Start of help text\n" +
"This is help text\n" +
"\n" +
"Wheee, here we go\n" +
...
"this is the end.");
btnCloseWindow = (Button) helpDialog.findViewById(R.id.btnCloseWindow);
btnCloseWindow.setText("Close");
btnCloseWindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpDialog.dismiss();
}
});
tvHelpDialogBody.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View tvHelpDialogBody, MotionEvent event) {
cancelCountdown();
startCountdown();
return false;
}
});
helpDialog.show();
return (helpDialog);
}
private void showHelpDialog() {
helpDialog = getHelpDialog();
helpDialog.show();
startCountdown();
}
synchronized private void startCountdown() {
handlerHelpDialogTimer.postDelayed(getCountdownTask(), COUNTDOWN_TIME_MS);
}
synchronized private void cancelCountdown() {
handlerHelpDialogTimer.removeCallbacks(runnableHelpDialogDismissCountdown);
runnableHelpDialogDismissCountdown = null;
}
private Runnable getCountdownTask() {
Runnable task = new Runnable() {
#Override
public void run() {
if (helpDialog != null) helpDialog.dismiss();
}
};
runnableHelpDialogDismissCountdown = task;
return task;
}
Ditch the countdown timer. Instead use a handler, for example:
public class AwesomeActivity extends Activity {
private static final int COUNTDOWN_TIME_MS = 300000;
Handler handler;
Runnable countDown;
Dialog helpDialog;
#Override public void onCreate(Bundle b) {
super.onCreate(b);
handler = new Handler();
}
/* call cancelCountdown() in onPause* */
private Dialog getHelpDialog() { return /* fill in the details */ }
private void showHelpDialog() {
helpDialog = getHelpDialog();
helpDialog.show();
startCountDown();
}
synchronized private void startCountDown() {
handler.postDelayed(getCountdownTask(), COUNTDOWN_TIME_MS);
}
synchronized private void cancelCountdown() {
handler.removeCallbacks(countdown);
countdown = null;
}
private Runnable getCountdownTask() {
Runnable task = new Runnable() {
#Override public void run() {
if (helpDialog != null) helpDialog.dismiss();
}
};
countDown = task;
return task;
}
}
Now in onTouch(MotionEvent e) you can cancel and start the countdown.
I'll leave it to you to figure out how to handle onPause and onResume :)
Furthermore, if you really wanted to, you could override a Dialog and put the Handler timer countdown logic inside that class, overriding show() to start the countdown and then add a method such as, restartTimer() you can call after a TOUCH_DOWN. If you do, you can then also override onSaveInstanceState and onRestoreInstanceState in the Dialog subclass, to cancel the callback, stash the time remaining, then pull out the time remaining and re-postdelay the countdown runnable with the remaining time.

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

Android Error: Undefined Method

I've got a Fragment (ActionBarSherlock Tabs), and I want to run a Chronometer in Background:
public class BFragment extends SherlockFragment {
private Button start;
private View v;
private Chronometer chrono;
private Button pause;
private Button reset;
private long lastPause;
private Button resume;
private boolean isChronometerRunning = false;
private boolean richtig = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.activity_bfragment, container, false);
start = (Button) v.findViewById(R.id.start);
chrono = (Chronometer) v.findViewById(R.id.chronometer1);
pause = (Button) v.findViewById(R.id.pause);
reset = (Button) v.findViewById(R.id.reset);
resume = (Button) v.findViewById(R.id.resume);
new ChronoBackground().execute();
return v;
}
void StartTimer() {
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
chrono.setBase(SystemClock.elapsedRealtime());
chrono.start();
isChronometerRunning = true;
System.out.println(SystemClock.elapsedRealtime());
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
lastPause = SystemClock.elapsedRealtime();
chrono.stop();
isChronometerRunning = false;
richtig = true;
}
});
resume.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (isChronometerRunning == false && richtig) {
chrono.setBase(chrono.getBase() + SystemClock.elapsedRealtime() - lastPause);
chrono.start();
richtig = false;
} else {
}
}
});
reset.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
chrono.setBase(SystemClock.elapsedRealtime());
System.out.println(chrono.getBase());
}
});
}
}
And here is my ChronBackground class/code:
public class ChronoBackground extends AsyncTask<Void, Void, Void> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
StartTimer();
return null;
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
#Override
protected void onPostExecute(Void result) {
return ;
}
#Override
protected void onPreExecute() {
return ;
}
}
Now there's an error, and I'm not really sure if my chrono is working this way... The error is at ChronoBackground: StartTimer() not defined.
The mistake is perhaps in the fact, that ChronoBackground is not an innerclass of BFragment and doesn't see the method?

Categories

Resources