i created a DialogFragment with a layout which contains a listview with some items and wanna do something with the value of the selected item but when i try to set the OnDismissListener it gives me an error.
If someone could help me, here is the code snippet where the error occurs.
When the execution reaches the dialog.getDialog().setOnDismissListener... then it gives the exception
FragmentManager manager = getFragmentManager();
PopupRecentBanderolNrs dialog = new PopupRecentBanderolNrs();
dialog.listitems[0] = GetFileContentsFromInternalStorage();
dialog.show(manager, "dialog");
manager.executePendingTransactions();
dialog.getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
... some code ..,
}
});
DialogFragment already implements DialogInterface.OnDismissListener, You can override the onDismiss() method in your PopupRecentBanderolNrs class.
if you want set your Listener, you can set in onCreateDialog method:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = ...;// your dialog
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
return dialog;
}
Related
When trying to use the back button of a dialog fragment
I'm curious as to the difference between using onBackPressed() (or onBackPressedCallBack) and onCancel().
I tried to define the data forwarding event of the back key using onBackPressedCallback() and OnBackPressedDispatcher() in the dialog fragment, but it didn't work.
In the end, I passed the data using onCancel().
Why doesn't the back key with onBackPressed() work?
UPDATED
public class WritingCommentDialogFragment extends DialogFragment {
OnBackPressedCallback callback;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return view;
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
callback = new OnBackPressedCallback(true) {
#Override
public void handleOnBackPressed() {
Toast.makeText(getContext(), "TEST", Toast.LENGTH_SHORT).show();
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
}
}
onBackPressed() of the dialog itself intercepts the back button press before the host Activity ever gets a shot at it. The default behavior is to call cancel() on the dialog and not pass it on to the Activity. That's why adding your callback to the Activity isn't doing anything. If you want to specifically handle the back button press, you would need to subclass Dialog to override it and use that class as the Dialog you create in onCreateDialog(). Something like this:
public class MyDialogFragment extends DialogFragment {
#NotNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Dialog dialog = new Dialog(requireContext(), getTheme()) {
#Override
public void onBackPressed() {
MyDialogFragment.this.onBackPressed();
// And maybe you also want to call cancel() here.
}
};
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
private void onBackPressed() {
// your code here
}
}
A dialog is canceled not only when back is pressed, but also if the user taps outside the dialog or presses the cancel button (if you added one to the dialog), or if you manually call cancel() on it or its host DialogFragment. So performing your action in onCancel() covers more events than just the back button being pressed.
A third possible event you can hook onto (with an OnDismissListener) is the dialog being dismissed, which is any time it is closed, including when it is canceled or when the screen rotates.
I don't understand DialogFragment at all. How to create one, how to get the user input out of it, and set it into a TextView.
I would like for the TITLE button, when clicked, to bring up a DialogFragment asking the user to enter the title of their Mood Board. The user enters a title. When they click the PostiveButton "Done", the user's title is set into the top left frame of the mood board, which has a TextView with a hint.
Please! Ask questions, because I don't really understand the dialog setup.
Here is a picture of my main_layout, in my MainActivity. Every element has an "#+id/".
The solution you are looking for is a callback:
Create an interface with a method to use as a callback
Implements the interface on the activity
Create the dialog fragment and in onAttach get the interface
Show the dialog fragment on the activity
On dismiss the dialog fragment pass the text using the instance of the interface
interface Callback {
updateText(String text)
}
class CoolActivity... implements Callback
onCreate {
//find your views
showDialogBtn.setOnClickListener(...
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("yourTag");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
DialogFragment dialogFragment = ExampleDialogFragment.newInstance();
dialogFragment.show(ft, "yourTag");
)
}
#Override
updateText(String text) {
youtView.setText(text)
}
class CoolDialogFragment extend DialogFragment {
private Callback callback;
#Override
void onAttach(Context context) {
callback = (Callback) context
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.dialog_fragment_example, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//find the views in the dialog fragment
closeBtn.clickListener(...
callback.updateText(edittext.getText().toString())
dismiss()
)
}
}
Here is a gist of a dialog fragment
https://gist.github.com/cutiko/7e307efcf7492ea52ef05cd90f9e3203
The problem is you want to connect a dialog fragment with a another component, and you want to do it straigth forward. This is not considered a good practice because yiu create 2 componentes higly attached, so the best would be to use data persistence and some form of react programming
You can make your mood board title textview static then call it to the alertdialog with edittext to set it text (setText)
like this.
final EditText edittext = new EditText(MainActivity.this);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Input Title")
.setView(edittext)
.setCancelable(false)
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
YourCustomDialog.your_title_textviewMoodboard.setText(edittext.getText().toString());
}
})
.setNegativeButton("Back", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
in your custom dialog. declare your textview static globally
public static TextView your_title_textviewMoodboard;
When I click on cardview dialog has to be opened. So this is my onClick method in fragment class.
public class Entry_Fragment extends Fragment implements
View.OnFocusChangeListener, View.OnClickListener {
public void onClick(View view) {
if(view == cdAddWork)
{
if(actvEntryCategory.getText().toString().trim().equals("Installation")){
try {
InstActivityDialog dlg;
dlg = new InstActivityDialog(getFragmentManager(),getActivity().getApplicationContext());
dlg.show();//here I am passing this fragment and context as parameters to the constructor in that dialog.
}catch (Exception e){
}
}
}
}
}
This is my dialog class
public class InstActivityDialog extends Dialog {
public InstActivityDialog(FragmentManager fm, Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.installation_dialog); //layout for dialog
setTitle("Installation Activity");
}
}
when I click on cardview in fragment, I need to open the dialog. For that In onClick method I call the dialog. I wanted to pass current fragment and context to the dialog.
What mistake I did while passing fragment and context as parameters to the constructor? And also while receiving argument in the constructor?
How to pass fragment and context as parameters?
Any help would be appreciated.
If your dialog is not showing then problem is in line blow.
InstActivityDialog dlg = new InstActivityDialog(getSupportFragmentManager(),getApplicationContext());
Dialog is bind to Activity's Context not Aplication Context. So use it like below.
InstActivityDialog dlg = new InstActivityDialog(getSupportFragmentManager(),getActivity());
dlg.show();
And for better implementation of Dialog with FragmentManager i suggest to use DialogFragment.
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've created a DialogFragment [implemented as AlertDialog with OnCreateDialog(Bundle)].
The DialogFragment asks for the user to input a project name (String) via an EditText box, and I'm trying to pass this back to the MainActivity.
In MainActivity, I use a Toast to check if the String has indeed been passed along. This check fails as nothing is passed. However, if I hardcode the String in my DialogFragment, it works. It leads me to suspect that there is a problem with the way I try to locate the EditText object, but I'm not sure what my mistake is.
MainActivity.java
public class MainActivity extends AppCompatActivity implements NewProjectDialog.NewProjectDialogListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize the two on screen buttons
//onclick listeners are attached to activity_main.xml
Button newProject = (Button) findViewById(R.id.new_project);
Button browseProjects = (Button) findViewById(R.id.browse_projects);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void newProject(View view) {
//Open up the DialogFragment that prompts user for the title
DialogFragment newFragment = new NewProjectDialog();
newFragment.show(getFragmentManager(), "New Project Dialog");
}
#Override
public void onDialogOK(String projectTitle) {
//Toast.makeText(MainActivity.this, projectTitle, Toast.LENGTH_SHORT).show();
}
#Override
public void onDialogCancel() {
//user pressed cancel in NewProjectDialog
Toast.makeText(MainActivity.this, "Cancelled", Toast.LENGTH_SHORT).show();
}
public void browseProjects(View view){
Toast.makeText(MainActivity.this, "Browse Projects", Toast.LENGTH_SHORT).show();
}
NewProjectDialog.java
public class NewProjectDialog extends DialogFragment{
/* The activity that creates an instance of this dialog fragment must
* implement this interface in order to receive event callbacks.
* Each method passes the DialogFragment in case the host needs to query it. */
public interface NewProjectDialogListener {
public void onDialogOK(String projectTitle);
public void onDialogCancel();
}
// Use this instance of the interface to deliver action events
NewProjectDialogListener mListener;
// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (NewProjectDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder newProjectDialog = new AlertDialog.Builder(getActivity());
//prevent dialog from closing
setCancelable(false);
//set dialog title
newProjectDialog.setTitle(R.string.new_project_title);
//inflate view so that findViewbyId on the next line works
View view = View.inflate(getActivity(),R.layout.new_project_dialog, null);
//Link tempEdit object to the text-edit box so we can retrieve data from it below upon button click
final EditText tempEdit = (EditText)view.findViewById(R.id.project_title);
//set the view
newProjectDialog.setView(R.layout.new_project_dialog);
//set OK button
newProjectDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Toast.makeText(getActivity(), tempEdit.getText().toString(), Toast.LENGTH_SHORT).show();
mListener.onDialogOK(tempEdit.getText().toString());
}
});
//set cancel button
newProjectDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogCancel();
}
});
// Create the AlertDialog object and return it
return newProjectDialog.create();
}
You're right, the problem is your taking an EditText from a different view. Because your layout is being inflated twice.
Try using setView(View) instead of the one with the layout resource id.