There is a fragment. When I press button on this fragment alert dialog is shown. This dialog is dissmissed after clicking on OK button. If I go to next fragment from current fragment and then come back - previous fragment is appeared with opened alert dialog. I use Cicerone for navigating. Maybe somebody faced with this problem?
// for navigating
router.navigateTo(screenKey);
// show dialog
AlertDialog alert = new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok, (dialog, which) -> dialog.dismiss())
.setCancelable(true)
.create();
alert.show();
// in my second fragment
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
showBackButton();
}
// in my main activity
#Override
public void showBackButton() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(Utils.getDrawable(this, R.drawable.ic_arrow_back_white_24dp));
toolbar.setNavigationOnClickListener(v -> {
onBackPressed();
});
}
#Override
public void onBackPressed() {
hideKeyboard();
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
hideDrawerLayout();
} else {
super.onBackPressed();
}
}
#Override
protected void onResume()
{
super.onResume();
dialog.close()
}
This will do the trick, in your parent activity where you are creating your dialog add this. Try to comment and uncomment super.onResume(); while testing.
What i got that You are navigating in first line and in next step you are showing the Dialog. These will execute one after another. I Hope you got my point . Do it as below :
AlertDialog alert = new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok, (dialog, which) ->
dialog.dismiss()// Optinal
router.navigateTo(screenKey);
)
.setCancelable(true)
.create();
alert.show();
And no need to dismiss the dialog, cause its the default behavior of AlertDialog.Let me know its solved your problem. Thanks.
Well, I have find a solution. Point is that Moxy framework is used in my project and I didn't set right state strategy type in my views. Now I use SkipStrategy to not pile up commands in the queue. Sorry for your time I spent :)
Related
I'm trying to make it so a clear button will open up an alert dialog which has a yes or no. When clicking the yes button, it should pass a bool value from the dialog frag to the other frag. If the value is true, which it should be when yes is clicked, it will call methods which will clear a database. Here is the dialog frag and the part of the frag where I'm trying to implement it. I can't get the dialog box to appear, but so far it does make the screen darker which I assume means I'm not hooking it up right.
Dialog frag:
public class DialogClear extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.clear_dialog, null);
final Button yes = dialogView.findViewById(R.id.yes);
final Button no = dialogView.findViewById(R.id.no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
return builder.create();
}
}
Here is how I'm trying to call it from my frag
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogClear = new DialogClear();
dialogClear.setTargetFragment(BloodPressureFragment.this, 1);
dialogClear.show(getFragmentManager(),"");
dataManager.clearDatabase();
dataManager.createDatabase();
dataText.setText("");
dataText.setBackgroundResource(R.drawable.no_border);
updateList();
}
});
welcome to code party
you have many choices to do this job, but i will show you best way for using fragments.
As you know, all fragments changes in one activity and extend from it.
So the easy way is this:
1.build public fields in your activity
2.build a getInstant method on activity
3.fill and get values of that activity from any fragments that you want show on this
see this example:
public boolean isLocationOn;
this field is build in activity
now:
in any fragment:
MainActivity.getInstance().isLocationOn = true;
in other fragment:
if(MainActivity.getInstance().isLocationOn){
//todo show map or ...
}
in this way you can use anything in fragments
update me in comments
You should read and try using 3 thing's to solve this.
1. Navigation Component
easy to navigate to fragment's and DialogFragment
2. View Model
Share same View Model between different fragment's of an activity
Data is not lost on Orientation change's
All business logic at one place and easy to unit test
3. Live Data
recommended for responsive ui
Easy to understand Api's
I'm creating a simple DialogFragment with two buttons, which is supposed only to show a Toast when you select any of the two options. This dialog is displayed when you press one certain button on a activity.
For some reason, the code doesn't show any kind of error but when i click the button, the app crashes.
How do I resolve this?
I was first trying to do a custom XML file and java file for the Dialog, but i couldn't make that work either. Google's documentation and other tutorials didn't help either
public class Config extends AppCompatActivity {
Button btncanc;
Button btnreestab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_config);
btncanc = (Button) findViewById(R.id.btncnacelset);
btnreestab = (Button) findViewById(R.id.btnrest);
btncanc.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast toast = Toast.makeText(getApplicationContext(),"OperaciĆ³n cancelada",Toast.LENGTH_SHORT);
toast.show();
Config.this.finish();
}
});
btnreestab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setMessage("Hola");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast toast = Toast.makeText(getApplicationContext(),"hola",Toast.LENGTH_SHORT);
toast.show();
}
});
builder.setNegativeButton("cancela", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast toast = Toast.makeText(getApplicationContext(),"adios",Toast.LENGTH_SHORT);
toast.show();
}
});
AlertDialog dialog = builder.create(); dialog.show();
}
});
}
}
You can copy your style from your context. Make your alert dialog initialization with.
new AlertDialog.Builder(Config.this)
in other way you can define a custom style in style.xml such as
<style name="myDialog" parent="Theme.AppCompat.Dialog">
<item name="android:windowNoTitle">true</item>
...
</style
and initialize alert dialog with
AlertDialog.Builder dialog = new AlertDialog.Builder(getApplicationContext(), R.style.myDialog);
The reason for this crash is the AppCompatActivity has the Theme.AppCompat so you should use this theme.
checkout that crash.
You need to use a Theme.AppCompat theme (or descendant) with this
activity
I am trying to develop a small app as a part of my exam. Basically, I have a button that goes to a webpage and I want an alert dialog to pop up when the button is clicked and before the web page opens. This is what I have so far:
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
webViewAndroidWeekly();
}
private void webViewAndroidWeekly (){
Button btnWebpage = findViewById(R.id.btnwebpage);
btnWebpage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://androidweekly.net/"));
startActivity(intent);
}
});
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "Thank you for using this app! :)", Toast.LENGTH_SHORT).show();
finish();
}
}
The button works and it opens the webpage so that part is set. I created a separate java class for the alert dialog and tried to implement it to work but I can't figure it out.
Dialog class:
public class InternetWarningDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIconAttribute(android.R.attr.alertDialogIcon);
builder.setTitle("Go to WebPage");
builder.setMessage("Are you sure you want to proceed to webpage? This may incur additional charges based on your mobile data plan!");
builder.setCancelable(false);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
getActivity().finish();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = builder.create();
return alertDialog;
}
}
create this method in mainActivity ...... Call this showDialog() method in your main Activity where you want
public void showDialog(){
InternetWarningDialog exampleDialog = new InternetWarningDialog();
exampleDialog.show(getFragmentManager(),"Internet Dialog");
}
If its works accept the answer
You have created the AlertDialog, but to get the Alert dialog view use the method show() on AlertDialog.Builder as shown below
AlertDialog alertDialog = builder.create();
builder.show();
I cannot see any call for AlertDialog. You need to add the call for AlertDialog along with AlertDialog.show() and then open the webpage if the user clicks on Yes.
AlertDialog alertDialog = builder.create();
builder.show();
A familiar question has already been asked before. Please refer this
open a dialog when i click a button
I am building an Android app that uses AlertDialog. I am following Google's guide to building an AlertDialog, but it keeps giving me an error. I set an onClickListener on a FAB, but it either never works or it throws an error.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab2);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("This is an alert dialog.").setTitle("alert dialog");
builder.create();
}
});
}
But the Android Studio throws an error, saying:
"error: cannot find symbol method getActivity()"
I've tried declaring a context variable and passing that, tried using getApplicationContext(), and getApplication(), but they all don't work.
What am I doing wrong?
Everything seems to be correct but some minor tweaks required in your code.
If you are going to display the alert dialog in the Activity use Activity.this , if it is in Fragment then use getActivity() during initialization of AlertDialog.Builder(*****).
Write the logic of the alert dialog in a separate function and call them in your clicklistener. Below code will help you.
void showAlert(){
// If using activity use this
AlertDialog.Builder adb = new AlertDialog.Builder(*YOUR ACTIVITY NAME*.this);
// If using Fragment use this
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
adb.setMessage("Alert Dialog Welcomes You");
adb.setTitle("Google alert dialog");
AlertDialog ad = adb.create();
ad.show();
}
Then call it in your fab onclicklistener.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab2);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAlert();
}
});
Happy coding..!!
If your class extend to activity, you should declare like this
AlertDialog.Builder builder = new AlertDialog.Builder(ActivityName.this);
If extend to fragment:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
It appears that Android Studio is bugged in some way. I would try to fix that by selecting "invalidate caches / restart" from the File menu.
That said, you can also get a context by getting it from the view.
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
//do your stuff here.
}
I created an AlertDialogFragment class and I am trying to show it from another class with the following code but I keep getting an error to change the type from FragmentTranscation to FragmentManager. If I change it to FragmentManager, I get a message to change to FragmentTranscation, whenever I change to FragmentTranscation, I get a message to change to FragmentManager:
Here is the code to show the alertDialog:
FragmentTransaction ft= getFragmentManager().beginTransaction();
AlertDialogFragment newFragment= new AlertDialogFragment();
newFragment.show(ft, "alertDialog");
Here is the code for the class:
public class AlertDialogFragment extends android.support.v4.app.DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder
= new AlertDialog.Builder(getActivity());
builder.setMessage("Staying in Touch With The Ones You Love");
builder.setTitle("Togetherness");
builder.setCancelable(false);
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
}
To show a fragment, you need to either replace an existing fragment or add a new one to an existing view.
Edit: Sorry, didn't notice it was a dialog fragment.
Use this:
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("alertDialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
newFragment.show(ft, "alertDialog");
And take a look at examples here : http://developer.android.com/reference/android/app/DialogFragment.html
Remember that fragments were introduced in API level 11. If you're using an older API level, follow the instructions here to use the Support Library for all your fragment stuff (I see your DialogFragment is already inheriting from support library FragmentDialog)
http://developer.android.com/training/basics/fragments/support-lib.html
Try use
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();