how to use a class in an activity? DialogFragment [duplicate] - java

This question already has answers here:
Custom Dialog Fragment
(2 answers)
Closed 4 years ago.
From Google Developer UI guide
You can accomplish a wide variety of dialog designs—including custom layouts and those described in the Dialogs design guide—by extending DialogFragment and creating a AlertDialog in the onCreateDialog() callback method.
For example, here's a basic AlertDialog that's managed within a DialogFragment:
What?
public class ResetAll extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.reset)
.setPositiveButton(R.string.reset2, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// code
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// code
}
});
return builder.create();
}
}
Use here the Class?
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
// USE HERE! DIALOG
}
return super.onOptionsItemSelected(item);
}

#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
// USE HERE! DIALOG
ResetAll dialog = new ResetAll();
dialog.show(getSupportFragmentManager(), "restFragmentDialog");
// restFragmentDialog is a unique tag name that the system uses to save and restore the fragment state when necessary.
// The tag also allows you to get a handle to the fragment by calling findFragmentByTag().
}
return super.onOptionsItemSelected(item);
}
From Google UI link mentioned on question.
Showing a Dialog
When you want to show your dialog, create an instance of your
DialogFragment and call show(), passing the FragmentManager and a tag
name for the dialog fragment.
You can get the FragmentManager by calling getSupportFragmentManager()
from the FragmentActivity or getFragmentManager() from a Fragment.

Related

How do I connect a button to a Dialog that will edit a TextView, within a FrameLayout, with a users input?

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;

DialogFragment OnDismissListener not working

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

Show A dialouge when app starts and Fix a Navigation Drawer issue

I have created a AlertDialogue. I want that when I open the App Dialogue will Show. Which method should I try? I tried onStart method but its doesn't works.
Here is the code:
#Override
protected void onStart() {
super.onStart(); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Quiz");
builder.setMessage("Are You Sure?");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"Ok was Clicked",Toast.LENGTH_SHORT).show();
finish();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"Ok was Clicked",Toast.LENGTH_SHORT).show();
finish();
}
});
}
On the Navigation Drawer I called a method . That method is created with a Alert Dialouge . When i click the item in Navigation Drawer its Shows 3-4 times continuously. i want that it will show only one time .
here is the code :
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.con_id) {
convertPointsToMoney();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
I want to add a Facebook group link on the navigation item. When I click on that item the browser will open and show the site.
Put the AlertDialogueinside onCreate()

Failed to pass String object from DialogFragment to MainActivity

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.

Dialog Box will not show

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

Categories