In activity there is an int with some value, the AlertDialog fragment is launched from the activity.

How to display this variable in this dialog?

Dialogue:

 import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; public class MyDialogFragment extends DialogFragment { int right = 0; int wrong = 0; @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("title") .setMessage("msg " + toString().valueOf(right) + " || " + toString().valueOf(wrong)) .setIcon(R.mipmap.ic_launcher) .setPositiveButton("Bullshit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent intent = new Intent(getContext(), MainActivity.class); startActivity(intent); } }); builder.setCancelable(false); return builder.create(); } } 

Activity code snippet:

 public void onAnsw3Click(View view) { Button button = (Button) findViewById(R.id.buttonAnsw3); String myText = button.getText().toString(); int tr = myText.indexOf(tempRight); if (tr == 0) { scoreRight++; } else { scoreWrong++; } createField(); } public void endGame() { FragmentManager manager = getSupportFragmentManager(); MyDialogFragment myDialogFragment = new MyDialogFragment(); myDialogFragment.show(manager, "dialog"); } 

Accordingly, you need to transfer scoreRight and scoreWrong and use them in the right and wrong place dialog.

Thank you in advance.

  • Add code first and second. - post_zeew
  • Thank you very much. I would continue to dig in the direction of Extras, and I would not have excavated it. - SGKiril

1 answer 1

You can transfer data to a fragment (when it is created) using fragment arguments:

In MyDialogFragment add the static method newInstance(...) :

 public static MyDialogFragment newInstance(int right, int wrong) { MyDialogFragment fragment = new MyDialogFragment(); Bundle args = new Bundle(); args.putInt("right", right); args.putInt("wrong", wrong); fragment.setArguments(args); return fragment; } 

and override the onCreate(...) method:

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); right = getArguments().getInt("right"); wrong = getArguments().getInt("wrong"); } 

In activity create a fragment instance using the newInstance(...) method:

 FragmentManager manager = getSupportFragmentManager(); MyDialogFragment myDialogFragment = MyDialogFragment.newInstance(scoreRight, scoreWrong); myDialogFragment.show(manager, "dialog");