HogeActivity.java
public class HogeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = findViewById(R.id.huga_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Display a dialog
DialogFragment dialog = new DialogFragment();
//Note: getFragmentManager()Will result in an error
dialog.show(getSupportFragmentManager(),"sample");
}
});
}
}
DialogFragment.java
public class BookReviewDialogFragment extends DialogFragment {
//Method called when dialog is generated
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Dialog generation Specify and instantiate the AlertDialog Builder class
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
//Title setting
dialogBuilder.setTitle("Dialog title");
//Text settings to display
dialogBuilder.setMessage("please fill in the value");
//Input field creation
final EditText editText = new EditText(getActivity());
dialogBuilder.setView(editText);
//Create OK button
dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Get value from editText
String returnValue = editText.getText().toString();
//Get an instance of HogeActivity
HogeActivity hogeActivity = (HogeActivity) getActivity();
hogeActivity.setTextView(returnValue);
}
});
//NG button creation
dialogBuilder.setNegativeButton("NG", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Close without doing anything
}
});
//returns dialogBulder
return dialogBuilder.create();
}
}
■ Refer to the character of the OK button of the dialog fragment from @strings
Resources res = getResources();
//Create OK button dialogBuilder.setPositiveButton(res.getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
Recommended Posts