in the following code work properly and show help screen when open activity but I want show one time forever,
what can i do?
What should I add in the code?
my code:
public class KhatmMain extends Activity implements OnClickListener{
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
setContentView(R.layout.khatmmain);
showOverLay();
.
.
.
}
private void showOverLay(){
final Dialog dialog = new Dialog(ctx, android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.overlay_view);
LinearLayout layout = (LinearLayout) dialog.findViewById(R.id.overlayLayout);
layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
dialog.show();
}
}
You can use SharedPrefereces to set a variable that will check if you've shown the dialog yet to the user or not, here's an example:
SharedPreferences prefs = this.getSharedPreferences("com.you.app", Context.MODE_PRIVATE);
Boolean dialogShown = prefs.getBoolean("dialogShown", false);
Then check if the value of dialogShown is false (you don't need to set it first since it will default to false the way we are calling it), then on the following code we execute some code, only if dialogShown is false, meaning we can do all the dialog stuff inside that conditional:
if(!dialogShown){
//Your show dialog code
prefs.edit().putBoolean("dialogShown",true).commit();
}
So the next time we check for the dialogShown value on the shared preferences it will be true therefor not showing the dialog. I believe this is the most common way of doing it.
There is a solution ..
when application first time start then save the shared preference to the app..
Now each and every time You retrieve the shared preference and check if it is there then move to next screen
Use this code:
public class KhatmMain extends Activity implements OnClickListener{
Context ctx;
Boolean showOneTime = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
setContentView(R.layout.khatmmain);
showOverLay();
.
.
.
}
private void showOverLay(){
if (showOneTime == false) {
return;
}
final Dialog dialog = new Dialog(ctx, android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.overlay_view);
LinearLayout layout = (LinearLayout) dialog.findViewById(R.id.overlayLayout);
layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
dialog.show();
showOneTime = false;
}
}
I want to show another alert message(alert box/alert dialog) after the progress bar reaches 100%. How do I do that?
And Also is there any way to style that box (or both of them)?
Below is my code for an ProgressBar:
public class MainActivity extends Activity {
Button progress_button;
ProgressDialog pro_dialog;
Handler pro_handler;
int progress;
private static final int MAX_PROGRESS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// intiliazing the buttons
progress_button = (Button) findViewById(R.id.button1);
progress_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Creating progress dialog interface setting
// title,progressstyle,max_progress
pro_dialog = new ProgressDialog(MainActivity.this);
pro_dialog.setTitle("Making everything OK is in progress! Please be patient.");
pro_dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pro_dialog.setMax(MAX_PROGRESS);
progress = 0;
pro_dialog.show();
pro_dialog.setProgress(0);
pro_handler.sendEmptyMessage(0);
}
});
// set onclick listener for buttons
pro_handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (progress >= MAX_PROGRESS) {
pro_dialog.dismiss();
} else {
progress++;
pro_dialog.incrementProgressBy(2);
pro_handler.sendEmptyMessageDelayed(0, 100);
}
}
};
}
First of all, it would make more sense if you could replace:
pro_dialog.incrementProgressBy(2);
with this:
pro_dialog.setProgress(progress);
Current code dismisses dialog after progress variable reaches MAX_PROGRESS, but current value of this variable isn't presented by the progress dialog.
If you would like to show AlertDialog, you can do it for example after "pro_dialog.dismiss()".
Case of Progress Dialog styling has been discused here.
I'm having the following issue developing in android 2.2 (API 8):
I have a customized Dialog class like this:
public AuthDialog(final Context context, OnDismissListener dismissListener, OnCancelListener cancelListener) {
super(context);
setOnDismissListener(dismissListener);
setOnCancelListener(cancelListener);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userpassdialog);
setTitle("Enter email and password");
setCancelable(true);
setCanceledOnTouchOutside(true);
authEmail = (EditText) findViewById(R.id.authEmail);
authPass = (EditText) findViewById(R.id.authPass);
alertMessage = (TextView) findViewById(R.id.auth_alert);
Button authButton = (Button) findViewById(R.id.authButton);
View.OnClickListener onClickListener = new View.OnClickListener() {
public void onClick(View v) {
if (checkCredentials())
dismiss();
else
showAlert();
}
};
authButton.setOnClickListener(onClickListener);
}
private void showAlert() {
alertMessage.setText("Wrong user/pass");
authEmail.setText(null);
authPass.setText(null);
}
private boolean checkCredentials() {
// Empty user/pass for now
boolean checkEmail = authEmail.getText().toString().equals("");
boolean checkPassword = authPass.getText().toString().equals("");
return checkEmail && checkPassword;
}
#Override
public void onBackPressed() {
cancel();
}
And I create a new AuthDialog like this:
private void authenticateThenAccept() {
OnDismissListener dismissListener = new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
accept();
}
};
OnCancelListener cancelListener = new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
cancel();
}
};
AuthDialog dialog = new AuthDialog(context, dismissListener, cancelListener);
dialog.show();
}
I'm using the debugger, and I see that when I cancel (using the back button or pressing outside the dialog) the app dismisses the dialog instead of cancelling.
Anybody has had this kind of issue with Dialogs?
Thanks in advanced.
onDismiss() is always fired when dialog closes. The documentation for setOnCancelListener() states: "This will only be invoked when the dialog is canceled, if the creator needs to know when it is dismissed in general, use setOnDismissListener", i.e. it's not either onCancel or onDismiss but both when a dialog is canceled. I agree though that it would have made more sense had that not been the case.
Assuming this dialog should be modal, make your dialog a new activity.
setCancelable(false) will prevent the back button from doing anything. Many developers just turn off the ability of the back button to close the dialog since it's unclear whether that is a cancel or ok action to the user.
I created a custom dialog that extends Dialog. One button on that the dialog is an “OK” button which the user is expected to press when finished entering information in other fields. I cannot get any listeners set to that button to fire.
public class HeightDialog extends Dialog {
private Button okButton;
…
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.heightdialog);
this.okButton = (Button)this.findViewById(R.id.userOkWithHeight);
this.okButton.setOnClickListener(new android.view.View.OnClickListener() {
public void onClick(View v) {
// Does not fire
HeightDialog.this.dismiss();
return;
}
});
this.okButton.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
// Does not fire
HeightDialog.this.dismiss();
return true;
}
});
this.okButton.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// Does not fire
HeightDialog.this.dismiss();
return true;
}
});
…
}
I also attempted an implementation where the Dialog class implemented the listeners(http://www.androidcompetencycenter.com/2009/01/android-basics-dialogs-and-floating-activities/) instead of using inner classes(http://about-android.blogspot.com/2010/02/create-custom-dialog.html):
Still no luck.
public class HeightDialog extends Dialog implements View.OnClickListener {
private Button okButton;
…
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.heightdialog);
this.okButton = (Button)this.findViewById(R.id.userOkWithHeight);
this.okButton.setOnClickListener(this);
public void onClick(View view){
HeightDialog.this.dismiss();
return;
}
…
}
I have set breakpoints inside each of the listeners in both versions of the implementation, and the debugger never stops execution. I have attempted to use inner classes for the listeners which did not solve the problem.
Any clues?
Thanks
I found a solution here:
Handling buttons in custom dialogs
It works in my case.
dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
Button dialog_btn = (Button) dialog.findViewById(R.id.dialog_button);
dialog_btn.setOnClickListener(new View.OnClickListener()
{
// Perform button logic
}
Why I am not sure why following the two examples mentioned in my post did not work, I figured out how to get it to work. I had to move the attachment of my listener to the button in the dialog's onStart() method from the dialog's onCreate() method.
It appear this is related to me also overriding the onStart() method in my custom dialog:
public void onStart() {
super.onStart();
setContentView(R.layout.heightdialog);
...
}
That code must have "zeroed" out my listeners which were in the onCreate() method.
In order to intercept button clicks HeightDialog must implement View.OnClickListener
public class HeightDialog extends Dialog implements View.OnClickListener
{
}
I need to dismiss system alert window on back pressed and home button event.I have tried with onKeyEvent but in vain. As we can't capture the back pressed event in a service, how to achieve this?
Since it's a service that hosting an overlay window, It's a bit tricky solution but it is possible.
You should handle these 2 cases separately (overriding home button press, and back button press).
1. Overriding home button press:
Create this HomeWatcher class which contains a BroadcastReceiver that will notify when home button was pressed. Register this receiver only when your window comes up.
Android: associate a method to home button of smartphone
Inside your service onCreate method use this:
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
#Override
public void onHomePressed() {
yourWindow.hide() //means: windowManager.removeView(view);
}
#Override
public void onHomeLongPressed() {
}
});
mHomeWatcher.startWatch();
2. Overriding back button press:
The idea is creating an empty layout as a data member of your window class,
and attach your view to it (even if its an inflated XML layout).
For example, this is gonna be your window class:
public class MyWindow
{
private WindowManager windowManager;
private WindowManager.LayoutParams params;
private View view;
// Add this empty layout:
private MyLayout myLayout;
public MyWindow()
{
windowManager = (WindowManager) context.getSystemService(context.WINDOW_SERVICE);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.your_original_window_layout, null);
// Add your original view to the new empty layout:
myLayout = new MyLayout(this);
myLayout.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
// And show this layout instead of your original view:
public void show()
{
windowManager.addView(myLayout, params);
}
public void hide()
{
windowManager.removeView(myLayout);
}
}
And now create the MyLayout class to override the back button press:
public class MyLayout extends LinearLayout
{
private MyWindow myWindow;
public MyLayout(MyWindow myWindow)
{
super(myWindow.context);
this.myWindow = myWindow;
}
#Override public boolean dispatchKeyEvent(KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
{
if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0)
{
getKeyDispatcherState().startTracking(event, this);
return true;
}
else if (event.getAction() == KeyEvent.ACTION_UP)
{
getKeyDispatcherState().handleUpEvent(event);
if (event.isTracking() && !event.isCanceled())
{
// dismiss your window:
myWindow.hide();
return true;
}
}
}
return super.dispatchKeyEvent(event);
}
}
I know it's a bit complicated as I said since it's a system alert window hosted by a service, BUT it's working. I have the same issue as well and it has been solved exactly like that.
Good luck.
use below method to handle back button pressed.
public void onBackPressed()
{
super.onBackPressed();
}
You need to overwrite the onBackPressed method.
#Override
public void onBackPressed() {
super.onBackPressed(); // remove this if u want to handle this event
}
Use the code below
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
//moveTaskToBack(false);
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you want to exit application?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
finish();
//close();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
#Override
public void onBackPressed()
{
super.onBackPressed();
}
Declare this on your activity. super.OnBackPressed automatically calls back method in android. it will surely cancel your dialog.
in addition, your dialog must look like this.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder1.setMessage("TEST DIALOG.\n");
builder1.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(MainActivity.this, "This Is test Dialog", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
or you can set Negative button..
Hope this helps!
Define a custom layout and override dispatchKeyEvent, for example:
public class CustomSystemAlertWindow extends FrameLayout {
public static final String TAG = "CustomSystemAlertWindow";
private WeakReference<Context> mContext;
public CustomSystemAlertWindow(Context context) {
super(context);
mContext = new WeakReference<Context>(context);
// Set a background color to identify the view on the screen
this.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
Log.d(TAG, "back button pressed");
if (mContext != null && mContext.get() != null) {
WindowManager wm = (WindowManager) mContext.get().getSystemService(Context.WINDOW_SERVICE);
wm.removeView(this);
}
return true;
}
return super.dispatchKeyEvent(event);
}
}
Then add the view with this code:
CustomSystemAlertWindow customSystemAlertWindow = new CustomSystemAlertWindow(context);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
PixelFormat.TRANSLUCENT);
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
wm.addView(customSystemAlertWindow, params);
When you press the back button the view will dismiss.
Show the Alert window through the Activity so you can detect it.
Implement the code to detect easily Back Button or Home Button pressed.
public class alertPopup extends Activity {
Context context;
final AlertDialog alertDialog;
String TAG = "your Activity Name"
boolean homePressed = false; // to detect the Homebutton pressed
#Override
public void onCreate(Bundle savedInstanceState) {
AlertDialog.Builder builder = newAlertDialog.Builder(YourActivity.this, R.style.AppCompatAlertDialogStyle);
builder.setTitle("AlertDialog Title");
..........
....... // Build ur AlertDialog
alertDialog= builder.create();
alertDialog.show();
//to detect Alert Dialog cancel when user touches outside the Dialog prompt
alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
Log.v(TAG,"Alert Dialog cancelled when user touches outside the Dialog prompt")
}
});
}
#Override
public void onBackPressed()
{
Log.v(TAG,"Back Button Pressed");
super.onBackPressed();
alertDialog.dismiss(); //dismiss the alertDialog
alertPopup.this.finish(); // Destroy the current activity
homePressed = false;
}
#Override
public void onResume() {
super.onResume();
homePressed = true; // default: other wise onBackPressed will set it to false
}
#Override
public void onPause() {
super.onPause();
if(homePressed) {
alertDialog.dismiss(); //dismiss the alertDialog
alertPopup.this.finish(); // Destroy the current activity
Log.v(TAG, "Home Button Pressed"); }
}
public void onDestroy(){
super.onDestroy();
}
}
Note:
Add this Permission in Android Manifest to show the alert Window .
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Happy Coding :)
I understand that you are using the <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> permission for showing a floating view.
Using a floating view you can intercept the back button press, but the home button press cannot be intercepted (android won't let you primarily because of security reasons).
To intercept the back button press you need to add a wrapper when you inflate your floating view.
Your wrapper should look like this:
// Wrapper for intercepting System/Hardware key events
ViewGroup wrapper = new FrameLayout(this) {
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
hideAddNotesFloatingView();
return true;
}
return super.dispatchKeyEvent(event);
}
};
Then you add it to your floating view as a root:
mAddNoteFloatingView = mInflater.inflate(R.layout.floating_add_note, wrapper);
My complete code looks like this:
private void addFloatingView() {
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_PHONE,
0,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER | Gravity.LEFT;
params.x = 0;
params.y = 0;
// Wrapper for intercepting System/Hardware key events
FrameLayout wrapper = new FrameLayout(this) {
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
// Add your code for handling the back button press
return true; // Return true means that the event was handled
}
return super.dispatchKeyEvent(event);
}
};
mAddNoteFloatingView = mInflater.inflate(R.layout.floating_view, wrapper);
mWindowManager.addView(mAddNoteFloatingView, params);
}
It's simple. Follow these steps:
Create a view like Relative Layout, Linear Layout or Frame Layout Dynamically. 2. Override the dispatchKeyEvent while creating the view.
Add your original view into this dynamically created view with addView() method.
Add the dynamically created view to your Window Manager or Alert Dialog whichever you want.
In addition to #Eliran Kuta's solution, this is more simple answer for Back button.
val view = getAlertView()
val windowParam = WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, // whatever
WindowManager.LayoutParams.WRAP_CONTENT, // whatever
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, // use WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY before Oreo
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, // whatever
PixelFormat.TRANSLUCENT // whatever
)
view.isFocusableInTouchMode = true
view.setOnKeyListener { view, keyCode, event ->
when (keyCode) {
KeyEvent.KEYCODE_BACK -> {
// do your work here
true
}
else -> false
}
}
val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowManager.addView(view, windowParam)