What I want is a dialog without any button, and closing that dialog when I click outside the dialog body. Is it possible?
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openCredit();
}
//THIS IS ONE CUSTOM DIALOG
public void openCredit(){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.activity_splash, null));
builder.show();
}
}
EDIT: I have search and found two functions setCanceledOnTouchOutside() and setCancelable(). First one is not working with my method of AlertDialog, giving error of "The method setCanceledOnTouchOutside(boolean) is undefined for the type AlertDialog.Builder". And 2nd one is just for pressing back button.
So, I change my code like below and it is now working. Thanks.
public void openCredit(){
AlertDialog builder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.activity_splash, null));
builder.setCancelable(true);
builder.show();
builder.setCanceledOnTouchOutside(true);
}
Have you tried this..
builder.setCancelable(true);
Add this line for doing this
builder.setCancelable(true);
Related
I need to reload an activity from another activity in android application. That 2nd activity is a dialog window, and based on the dialog window base activity should refresh the contents. (By click button of dialog activity)
Reload your activity.
context.startActivity(context.getIntent());
context.finish();
Consider A is an activity you want to reload and B is another activity.
In this case, just call finish()
when you are moving from A to B. When you call A from B it will load the activity A again.
Dialog Window and activity is completely deferent things.
It is possible to refresh First Activity from it's dialog. You can do it using interface.
Here is simple solution. In your First Activity implements a Interface name IRefreshInteface. It's definition is like bellow:
public interface IRefreshInteface(){
public void doRefreshValue(String commandValue);
}
Now if you implement IRefreshInteface in your activity you will get method doRefreshValue(String commandValue) and write refresh code here.
#Override
void doRefreshValue(String commandValue){
// Write refresh code here
}
Now in your dialog you have Context of your Activity. Using that context object you can call this doRefreshValue(String commandValue) method easily. Here is the sample code :
public AlertDialog displayMessage(Context context, String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
LayoutInflater inflater = LayoutInflater.from(context);
final View v = inflater.inflate(R.layout.custom_view, null);
builder.setView(v);
shipText = (EditText)v.findViewById(R.id.shipNameEditText);
scientistNameText = (EditText)v.findViewById(R.id.scientistEditText);
scientistEmailText = (EditText)v.findViewById(R.id.emailEditText);
volumeText = (EditText)v.findViewById(R.id.volumeEditText);
colourText = (EditText)v.findViewById(R.id.colourEditText);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((IRefreshInteface) context).doRefreshValue("YOUR_COMMAND");
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog= builder.create();
dialog.show();
Button tb = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
tb.setOnClickListener(new CustomListener(dialog));
return dialog;
}
here, pass Context of Activity todisplayMessage() method and call activity method doRefreshValue using this way:
((IRefreshInteface) context).doRefreshValue("YOUR_COMMAND");
For more info visit here and here
Hope this will solve your problem. Sorry for bad english :)
I want to show a custom dialog box when I start my first activity without using a button. I try to search but I'm not finding the proper solution what I really want to do. Many of them are using onClick Listener to achieve that the scenario. Below image is showing an activity with a dialog box, that's what I'm looking for but without using onClick Listener.
How can we implement without using onClick Listener?
Any code contained in a click listener also works elsewhere in the class (unless you use the view that's clicked)
Create the dialog in onCreate. It will open immediately when the activity is started
In your main Activity oncreate method:
createCustomizeDialog();
now create this method outside of oncreate:
private void createCustomizeDialog() {
final AlertDialog.Builder builder=new AlertDialog.Builder(this);
LayoutInflater inflater = getActivity().getLayoutInflater();
#SuppressLint("InflateParams") final View alertLayout = inflater.inflate(R.layout.customize_dialog, null);
Button submit=(Button)alertLayout.findViewById(R.id.sButton);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
builder.setView(alertLayout);
alertDialog=builder.create();
//noinspection ConstantConditions
alertDialog.show();
}
Just try this way
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("TADAAAA!").create().show();
}
If you want to show the dialog only for the FIRST launch of this activity, you should put the code for your dialog in onCreate method of this activity, if it should be done for EVERY launch of this activity - then in onStart() method.
I'm building an Android application and that aplication have an open part and some actions that need authentication.
What I do is to when the user click on an action that needs authentication a login dialog is show, the user can login and the login will be valid for 30 minutes.
So I have 3 buttons in an fragment that when clicked check if the user is logged in, an if not calls a login dialog.
The problem is: How can I identify what button was clicked, because when the user click the button and is not authenticated I just create the login dialog and set the setTargetFragment to the caller fragment, that was the same for the 3 buttons.
Is there a way to pass a parameter to the login dialog to identify that?
The code are as following:
When the user click the button:
final DialogFragment loginDialog = new LoginDialogFragment();
loginDialog.setTargetFragment(this, 0);
btnAprovar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!LoginService.getInstance().isLoggedOn()) {
loginDialog.show(getFragmentManager(), "Login");
}
}
});
And In the dialog:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.fragment_login_dialog, null);
final EditText txtUser = (EditText) v.findViewById(R.id.txtUsername);
final EditText txtPwd = (EditText) v.findViewById(R.id.txtPassword);
builder.setView(v)
.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
DoLogin dl = new DoLogin();
dl.execute(txtUser.getText().toString(), txtPwd.getText().toString());
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LoginDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
private void DoPost(Boolean _result) {
if (_result.equals(true)) {
((PublicacaoDetailFragment) this.getTargetFragment()).onAuthTrue();
} else {
((PublicacaoDetailFragment) this.getTargetFragment()).onAuthFalse();
}
}
What is the best Practice to do that?
Thanks
To extend #Rodolfo's answer, you should probably use the decorator/wrapper pattern here.
Instead of extending DialogFragment, in your LoginDialogFragment you should just have an instance variable of a DialogFragment. This way, you can have a method called show(String buttonDescription), for example. Inside your own show(...) method, you can call the show() method of the DialogFragment.
Since you are extending DialogFragment in a class of your own, you have two choices:
Define a variable (with getter and/or setter) inside your custom Dialog class. In your login button onClick method, before calling show() of your Dialog, call the setter for this variable and pass v.getId(). In this case, v is the View associated with the component that you've added the OnClickListener.
Pass your button View id within a Bundle to your DialogFragment.
I'm popping up an AlertDialog when a ListView item is clicked and the string of the message is very large (nearly 20,000 characters). What winds up happening is that I click the list item and it sits for about 3-4 seconds before displaying the AlertDialog. This is problematic for many reasons, primarily that the user could click the button repeatedly and crash the app.
My first thought was to try to mimic how the Google Play app handles their open source license display (Play -> Nav Drawer -> Settings -> Open Source License info), where they pop open the AlertDialog and then it looks as though the view/text is loaded after the dialog is shown. I imagined it looking something like this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
builder.setMessage(veryLongStringMessage);
builder.setCancelable(true);
builder.setNeutralButton(android.R.string.ok, listener);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
Pretty basic stuff up until this point. Then I've tried to remove the message set in builder for something like:
builder.setMessage("")
// create/show dialog as above
alertDialog.setMessage(veryLongStringMessage);
But that seems to just load the whole dialog before showing it. So I thought maybe post a runnable to go at the end of the activity calls, and that wasn't working. I tried doing this in an Async task and could not get it working that way either. I've tried this as a DialogFragment where I call
activity.getSupportFragmentManager().executePendingTransactions();
Then go on to try to set the message after I know the DialogFragment has been shown and I either wind up with an empty dialog (the new message won't show up) or it loads it all at once and I'm sitting with that 3-4 second delay.
Anyone have any good method of implementing and AlertDialog with a very large message?
This case is when I show the legal notices of Google Play Services:
The problem seems to be the Dialog.show(), it takes those seconds in order to generate the layout.
So what I have done in my case, probably not the best one but it works. I create a temporal dialog.
private void showGPSLicense() {
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MyActivity.this);
LicenseDialog.setTitle(getString(R.string.google_maps_legalnotices));
LicenseDialog.setMessage(getString(R.string.google_maps_loading));
final Dialog loadingDialog = LicenseDialog.create();
loadingDialog.show();
//This dialog does not take much time. Meanwhile I get via AsyncTask the heavy message, replacing/dismissing the previous dialog.
(new AsyncTask<Void, Void,AlertDialog.Builder>() {
#Override
protected AlertDialog.Builder doInBackground(Void... arg0) {
String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(getApplicationContext());
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MyActivity.this);
LicenseDialog.setTitle(getString(R.string.google_maps_legalnotices));
LicenseDialog.setMessage(LicenseInfo);
return LicenseDialog;
}
protected void onPostExecute(AlertDialog.Builder result) {
Dialog dialog = result.create();
dialog.setOnShowListener(new OnShowListener() {
public void onShow(DialogInterface dialog) {
loadingDialog.dismiss();
}
});
dialog.show();
}
}).execute();
}
Tested on Nexus 5 (4.4.2)
If you are worried about many clicks you can also prevent many clicks by implementing the OnClickListener:
public abstract class PreventManyClicksListener implements OnClickListener {
private boolean clickable = true;
public abstract void preventManyClicks(View view);
public final void onClick(View view) {
if (clickable) {
clickable = false;
preventManyClicks(view);
}
}
public void setClickable() {
clickable = true;
}
}
//...
private PreventManyClicksListener preventDialog = new PreventManyClicksListener() {
#Override
public void preventManyClicks(View view) {
showGPSLicense();
setClickable();
}
};
//..
myView.setOnClickListener(preventDialog);
I think you need to use a custom view in order to be able to do this, because you can't update an AlertDialog message after it's been created. Create a custom view with a TextView with an id of textView1 and ProgressBar with id of progressBar1 then create the following class.
public class MyDialogFragment extends DialogFragment {
private TextView mTextView;
private ProgressBar mProgressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_dialog, container, false);
mTextView = view.findViewById(R.id.textView1);
mTextView.setVisibility(View.GONE);
mProgressBar = view.findViewById(R.id.progressBar1);
mProgressBar.setVisibility(View.VISIBILE);
return view;
}
#Override
public View onStart() {
super.onStart();
mTextView.setText(getArguments().getString("text");
mProgressBar.setVisibility(View.GONE);
mTextView.setVisibility(View.VISIBILE);
}
}
You also need to pass it the text string in its arguments.
DialogFragment dialog = new MyDialogFragment();
Bundle args = new Bundle();
args.putString("text", text);
dialog.setArguments(args);
dialog.show(getFragmentManager(), "my_dialog")
I have a subclass of ListActivity that is reused throughout my project, subclassed again so that each reports to a different ActivityGroup. This is working beautifully until I try to present a dialog in the superclass (as this behaviour should be exhibited by each subclass), and I get the following error:
ERROR/AndroidRuntime(31514): FATAL EXCEPTION: main
ERROR/AndroidRuntime(31514): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Now, I think this is due to the context that is being fed into the AlertDialog.Builder. I am using standard sample code from Google. Any ideas appreciated.
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
The problem here is that the activity is part of an ActivityGroup. You cannot open a dialog with a context of the current activity in the ActivityGroup, instead provide the context of the ActivityGroup itself.
In the Activity from which you want to present the dialog:
ProgressDialog dialog = new ProgressDialog(MyActivityGroup.group);
In the ActivityGroup subclass, MyActivityGroup, define your static reference:
public static MediaMenuGroup group;
then
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
group = this;
...