I have a DialogFragment in which I pass on my custom layout and this layout contains 2 buttons (Which correspond to the style of the application). How to access them?

This is what my DialogFragment class looks like:

 public class MyDialog extends DialogFragment { final String LOG_TAG = "MyDialog"; int layout; @Override public void onCreate(Bundle savedState) { super.onCreate(savedState); Bundle args = this.getArguments(); layout = args.getInt("layout"); } public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder adb = new AlertDialog.Builder(getActivity()) .setView(layout) .setCancelable(true); return adb.create(); } public void dismissDialog(final MyDialog dialog, int daleyTime) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { try { dialog.dismiss(); } catch (IllegalStateException e) { e.printStackTrace(); } } }, daleyTime); } public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); Log.d(LOG_TAG, "MyDialog: onDismiss"); } public void onCancel(DialogInterface dialog) { super.onCancel(dialog); Log.d(LOG_TAG, "MyDialog: onCancel"); } public static MyDialog newInstance(int layout) { MyDialog myDialog = new MyDialog(); Bundle args = new Bundle(); args.putInt("layout", layout); myDialog.setArguments(args); return myDialog; } } 

How to install the licenser on the layout buttons that I pass to the DialogFragment ?

    1 answer 1

    Try this:

     @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(layout, null); Button button = (Button)view.findViewById(R.id.button); button.setListener(...); builder.setView(view); return builder.create(); } 
    • It seems everything is clear, that's just why setView(view); ? Well, as I understand, I’ve found a setView(view); they’ve set a lister, why setView(view); ? And one more question, I have several classes using this dialog, and only one class passes the layout with buttons ... I now wonder if the code will fly out with this approach if I transmit activations without buttons ... How the inflator will look for them. .. Likely to fly ... Can I get around this? - Aleksey Timoshchenko
    • @AlekseyTimoshchenko, 1) Well, you need to populate this dialogue with the dialogue, you can also find layout in your code 2) You can go around this way: Button button = (Button)view.findViewById(R.id.button); if( button != null) button.setListener(...); Button button = (Button)view.findViewById(R.id.button); if( button != null) button.setListener(...); - katso