I am trying to pass Information from my AlertDialog to the parent Fragment it is on. But as soon as you klick the positive button, the app will crash.
I dont really know what todo anymore already read many Posts and articles but could not find the Problem.
Would be great if you could help me out.(Im a beginner)
Here is the Error I get with the first Problem in Code and the second commented.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.test, PID: 20682
java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.test.SchulfachDialog$SchulfachDialogListener.applyTexts(java.lang.String)' on a null object reference
at com.example.test.SchulfachDialog$1.onClick(SchulfachDialog.java:39)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5525)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
here is my code for the alert Dialog:
builder.setView(view)
.setTitle("Add new subject")
.setMessage("Message")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String name = editTextName.getText().toString();
listener.applyTexts(name); // Problem 1: when positiv Button is pushed this line causes a crash
}
});
editTextName = view.findViewById(R.id.edit_name);
return builder.create();
}
this is the applyTexts which I override in the fragments Code:
public interface SchulfachDialogListener{
void applyTexts(String name);
}
}
#Override public void applyTexts(String name) {
test = name;
}
}
I also have this block in which the 2 commented lines cause a crash when clicking on the button which starts the alert Dialog:
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (SchulfachDialogListener) context;
} catch (ClassCastException e) {
// throw new ClassCastException(context.toString()+
// "must implement SchulfachDialogListener");
}
}
Solution: To pass data from an alert dialog to a parent fragment, the easier way is let the dialog extends DialogFragment. Then using setTargetFragment and setTargetFragment to send data between them.
Because you do not post parent fragment code, so I assume here is xml and java code of your parent fragment.
MainFragment.java
public class MainFragment extends Fragment implements SchulfachDialogListener{
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button btnShowAlertDialog = view.findViewById(R.id.button_show_alert_dialog);
btnShowAlertDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SchulfachDialog dialog = new SchulfachDialog();
dialog.setTargetFragment(MainFragment.this, 0);
dialog.show(requireActivity().getSupportFragmentManager(), null);
}
});
return view;
}
#Override
public void applyTexts(String text) {
Toast.makeText(requireActivity(), text, Toast.LENGTH_SHORT).show();
}
}
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Alert Dialog"
android:id="#+id/button_show_alert_dialog"/>
</LinearLayout>
Let the alert dialog extends DialogFragment.
public class SchulfachDialog extends DialogFragment {
private EditText editTextName;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
View view = LayoutInflater.from(requireActivity()).inflate(R.layout.dialog_schulfach, null);
builder.setView(view)
.setTitle("Add new subject")
.setMessage("Message")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String name = editTextName.getText().toString();
SchulfachDialogListener listener = (SchulfachDialogListener) getTargetFragment();
listener.applyTexts(name);
}
});
editTextName = view.findViewById(R.id.edit_name);
return builder.create();
}
}
Related
I've seen other posts but can't make heads nor tails of the following error.
Trying to have a dialog pop up on Recycler View item. I do have a similar dialog that works. I must use a different dialog because of different options in the second instance.
public class EditItemDialog extends AppCompatDialogFragment{
private EditText projectAmountEditText;
private EditDialogListener listener;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.activity_inventory_item, null);
builder.setView(v)
.setTitle("Edit Amount")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
int amountChanged = Integer.parseInt(projectAmountEditText.getText().toString());
listener.editAmount(amountChanged);
}
});
projectAmountEditText = v.findViewById(R.id.amount_edit_text_item_activity);
if(projectAmountEditText == null){
//TODO
}
builder.show();
return builder.create();
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
listener = (EditDialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() +
"must implement EditDialogLister");
}
}
public interface EditDialogListener{
void editAmount(int amountChanged);
}
}
Here is the logcat
Process: com.x.x, PID: 8485
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:5235)
at android.view.ViewGroup.addView(ViewGroup.java:5064)
at android.view.ViewGroup.addView(ViewGroup.java:5036)
I had to add a onDestroy override on the dialog to free the View.
I have created a custom dialog showing a grid of items. When another option is clicked, it will also open another custom dialog with an editText field. The problem I am facing is getting a null object error for the textfield. I found an answer here but when I applied it, the result is still the same.
Basically, the app is crashing when retrieving the textfield value in the custom dialog that opens from another custom dialog. Here is what I have so far:
onCreate()
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button donate = findViewById(R.id.button);
donate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDonateDialog();
}
});
}
showDonateDialog()
//Donate dialog with grid options
private void showDonateDialog() {
// Prepare grid view
GridView gridView = new GridView(this);
String[] donateAmount = getResources().getStringArray(R.array.donationAmount);
List<String> donateList = new ArrayList<String>();
Collections.addAll(donateList, donateAmount);
gridView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, donateList));
gridView.setNumColumns(3);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Thank you for your donation!", Toast.LENGTH_SHORT).show();
}
});
// Set grid view to alertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(gridView);
builder.setTitle("Donate");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setNeutralButton("Other amount", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showCustomDonate();
}
});
builder.setCancelable(false);
builder.show();
}
showCustomDonate()
//Donate dialog for custom amount
private void showCustomDonate() {
AlertDialog.Builder builderCustom = new AlertDialog.Builder(this);
Context context = builderCustom.getContext();
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.custom_donate_amount, null, false);
final EditText donateAmount = findViewById(R.id.editAmount);
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
dialog.cancel();
} else {
String amount = donateAmount.getText().toString(); //Error null object reference here
Toast.makeText(getApplicationContext(), "Thank you for donating " + amount, Toast.LENGTH_LONG).show();
}
}
};
builderCustom.setView(view)
.setTitle("Custom Donation")
.setCancelable(false)
.setPositiveButton("OK", listener)
.setNegativeButton("CANCEL", listener)
.show();
}
Log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.customdialog, PID: 12011
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.customdialog.MainActivity$5.onClick(MainActivity.java:94)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
i hope it is work for you
showCustomDonate()
//Donate dialog for custom amount
private void showCustomDonate() {
AlertDialog.Builder builderCustom = new AlertDialog.Builder(this);
Context context = builderCustom.getContext();
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.custom_donate_amount, null, false);
final EditText donateAmount = findViewById(R.id.editAmount);
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
dialog.cancel();
} else {
String amount = donateAmount.getText().toString(); //Error null object reference here
Toast.makeText(getApplicationContext(), "Thank you for donating " + amount, Toast.LENGTH_LONG).show();
}
}
};
builderCustom.setView(view)
.setTitle("Custom Donation")
.setCancelable(false)
.setPositiveButton("OK", listener)
.setNegativeButton("CANCEL", listener)
.show();
}
Change on this line
final EditText donateAmount = view.findViewById(R.id.editAmount);
I created a custom AlertDialog and I want to save the values that the user has set. However I can't access them because Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference.
I am in HomeFragment, I created the AlertDialog and set the layout. I did it like this :
public class HomeFragment extends Fragment implements CustomDialog.CustomDialogListener {
private HomeViewModel homeViewModel;
private View root;
public View onCreateView(#NonNull final LayoutInflater inflater,
final ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
root = inflater.inflate(R.layout.fragment_home, container, false);
final TextView textView = root.findViewById(R.id.text_home);
homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
Button btn_add_apero = (Button) root.findViewById(R.id.btn_add_apero);
btn_add_apero.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(root.getContext());
builder.setTitle("Super un nouvel apéro !");
final EditText name_apero = (EditText)root.findViewById(R.id.edit_apero);
final EditText date_apero = (EditText)root.findViewById(R.id.edit_date);
builder.setView(inflater.inflate(R.layout.layout_dialog, null))
// Add action buttons
.setPositiveButton(R.string.text_add, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
LaperoDatabase db = Room.databaseBuilder(root.getContext(),
LaperoDatabase.class, "lapero_db").allowMainThreadQueries().build();
AperoDao dbApero = db.getAperoDao();
Apero new_apero = new Apero(name_apero.getText().toString(), date_apero.getText().toString());
dbApero.insert(new_apero);
}
})
.setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
});
return root;
}
In my layout_dialog.xml I set the 2 EditText :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<EditText
android:id="#+id/edit_apero"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/edit_apero" />
<EditText
android:id="#+id/edit_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/edit_apero"
android:layout_alignParentStart="true"
android:hint="#string/edit_date"
android:layout_alignParentLeft="true" />
</RelativeLayout>
How can I manage to get the value that are in those 2 fields ?
First thing i noticed is that you're using root to find your dialog views, but root points to your fragment layout. root = inflater.inflate(R.layout.fragment_home, container, false);
First inflate your dialog layout before referencing its resource id.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View inflater = getLayoutInflater().inflate(R.layout.layout_dialog, null);
builder.setView(inflater);
Then change root to inflater so you reference the view from your dialog layout
final EditText name_apero = (EditText)inflater.findViewById(R.id.edit_apero);
final EditText date_apero = (EditText)inflater.findViewById(R.id.edit_date);
Full code
Button btn_add_apero = (Button) root.findViewById(R.id.btn_add_apero);
btn_add_apero.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
View inflater = getLayoutInflater().inflate(R.layout.layout_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(inflater);
builder.setTitle("Super un nouvel apéro !");
final EditText name_apero = (EditText)inflater.findViewById(R.id.edit_apero);
final EditText date_apero = (EditText)inflater.findViewById(R.id.edit_date);
// Add action buttons
builder.setPositiveButton(R.string.text_add, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
LaperoDatabase db = Room.databaseBuilder(root.getContext(),
LaperoDatabase.class, "lapero_db").allowMainThreadQueries().build();
AperoDao dbApero = db.getAperoDao();
Apero new_apero = new Apero(name_apero.getText().toString(), date_apero.getText().toString());
dbApero.insert(new_apero);
}
})
builder.setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
});
AlertDialog displays the content and buttons perfectly until the contents grow to the point that scrolling is required to display it all. At that point the buttons disappear, even though the list shows in its entirety.
I see that in years gone by this question was asked (this one is essentially identical to mine (DialogFragment buttons pushed off screen API 24 and above), but the answers all seemed hit or miss, haphazard even: setting layout_weight, switching from setMessage() to setTitle(), and finally switching away from AlertDialog to Dialog.
None of these are working form me, and avoiding AlertDialog is NOT an appealing option because I am using the setMultiChoiceItems() method that seems (incredibly to me, perhaps given my extremely limited knowledge) available only to AlertDialog.
Thus in desperation and frustration I appeal directly to the collective brains of stackoverflow.
This is a pared down version of my DialogFragment:
public class SurfaceDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = requireActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.surface_dialog, null))
.setTitle(mMessage)
.setMultiChoiceItems(mSurfaceList, mCheckedSurfaces, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
mCheckedSurfacesPositions.add(which);
} else {
mCheckedSurfacesPositions.remove(mCheckedSurfacesPositions.indexOf(which));
}
}
});
// builder.setCancelable(false);
builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ProcessDialogSelections(mCheckedSurfacesPositions);
dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listener.onSurfaceDialogSelectedSent(mUnitSurfaces);
dismiss();
}
});
return builder.create();
}
That not working, I then coded my own buttons and displayed them:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = requireActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.surface_dialog, null);
builder.setView(dialogView)
.setTitle(mMessage)
.setMultiChoiceItems(mSurfaceList, mCheckedSurfaces, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
mCheckedSurfacesPositions.add(which);
} else {
mCheckedSurfacesPositions.remove(mCheckedSurfacesPositions.indexOf(which));
}
}
});
Button positiveButton = dialogView.findViewById(R.id.positive_button);
Button negativeButton = dialogView.findViewById(R.id.negative_button);
positiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProcessDialogSelections(mCheckedSurfacesPositions);
dismiss();
}
});
negativeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onSurfaceDialogSelectedSent(mUnitSurfaces);
dismiss();
}
});
return builder.create();
}
and here is my revised XML file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
android:orientation="vertical">
</ScrollView>
<Button
android:id="#+id/positive_button"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:layout_width="wrap_content"
android:text="Done"
app:layout_constraintBaseline_toBaselineOf="#+id/negative_button"
app:layout_constraintEnd_toStartOf="#+id/negative_button"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/negative_button"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:layout_width="wrap_content"
android:text="Cancel"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/positive_button" />
</androidx.constraintlayout.widget.ConstraintLayout>
And with THAT not working, I then followed the advice of Vikas Singh (AlertDialog Buttons not visible when using Custom layout). This is what the new code looks like (essentially creating the layout in Java rather than XML.
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// New code from Vikas Singh
LinearLayout rootLayout = new LinearLayout(getActivity());
rootLayout.setOrientation(LinearLayout.VERTICAL);
ScrollView scrollView = new ScrollView(getActivity());
LinearLayout layout = new LinearLayout(getActivity());
layout.setOrientation(LinearLayout.VERTICAL);
scrollView.addView(layout);
rootLayout.addView(scrollView);
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton("Go", null);
builder.setView(rootLayout);
builder//.setView(dialogView)
//.setTitle(mMessage)
.setMultiChoiceItems(mSurfaceList, mCheckedSurfaces, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
mCheckedSurfacesPositions.add(which);
} else {
mCheckedSurfacesPositions.remove(mCheckedSurfacesPositions.indexOf(which));
}
}
});
return builder.create();
}
Still no buttons when I have to scroll.
Why not and what can I do about it?
Here is the solution:
public class SurfaceDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//LayoutInflater inflater = requireActivity().getLayoutInflater();
builder
//.setView(inflater.inflate(R.layout.surface_dialog, null)) didn't work
// nor did setView with android.R.layout.select_dialog_multichoice
// nor android.R.layout.simple_list_item_multiple_choice work
.setTitle(mMessage)
.setMultiChoiceItems(mSurfaceList, mCheckedSurfaces, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
mCheckedSurfacesPositions.add(which);
} else {
mCheckedSurfacesPositions.remove(mCheckedSurfacesPositions.indexOf(which));
}
}
});
// builder.setCancelable(false);
builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ProcessDialogSelections(mCheckedSurfacesPositions);
dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listener.onSurfaceDialogSelectedSent(mUnitSurfaces);
dismiss();
}
});
return builder.create();
}
The multiChoiceItems DialogFragment now works like a charm!
All I had to do was simply comment out the above lines.
As a result, there is no layout explicitly inflated, no view set.
But it works nonetheless.
Now I would love it if someone could explain to me
the details of why this works,
why the other did not, and
in light of the earlier failure, how could a custom layout be implemented to achieve this result of not losing the action buttons when the view scrolled
I have a MainActivity like this one below:
My question is how to open a DialogFragment clicking on the TextView "click HERE to give a name to the task" placed next to "play" button.
Here is the code of my TextView:
TextView buttonView = new TextView(this);
buttonView.setHint("click HERE to give a name to the task");
buttonView.setX(50);
buttonView.setY(50);
and the code of the DialogFragent:
public class ButtonNameDialogFragment extends DialogFragment {
private IFragment iButNamFrag;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder setButNameAlert = new AlertDialog.Builder(getActivity());
setButNameAlert.setTitle("Set Task name");
LayoutInflater inflater = getActivity().getLayoutInflater();
setButNameAlert.setView(inflater.inflate(R.layout.button_name_fragment, null))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Implement dialogPositiveClick
}
})
.setNegativeButton(R.string.undo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Implement dialogNegativeClick
}
});
return setButNameAlert.create();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
iButNamFrag = (IFragment) activity;
}
}
and here is the interface:
public interface IFragment {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
You can set an onClickListener to any view in Android and then perform any behavior you would like
buttonView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create new DiaglogFragment and display it
}
};
This is the same method used for any kind of button pressing. There are plenty of other answers already out on StackOverflow with further examples of this. If you need more information on tap recognition or displaying fragments, a quick search will find it on Stack.
buttonView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment frag = new ButtonNameDialogFragment();
frag.show(*context*, ButtonNameDialogFragment.class.getCanonicalName());
}
});