Добавление положительной/отрицательной кнопки в диалог DialogFragment
Я уже написал DialogFragment. Теперь я понял, что хочу, чтобы у него была положительная и отрицательная кнопки, как у AlertDialog. Как я могу достичь такой цели, поддерживая написанный мной код?
public class DoublePlayerChooser extends DialogFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL,0);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("title")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do something...
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.doubleplayerchooser, container, false);
getDialog().setTitle("Enter Players");
firstPlayerPicker = (ImageButton) v.findViewById(R.id.imageButton1);
firstPlayerPicker.setOnClickListener(new OnClickListener() {
public void onClick(final View v){
callContactPicker(1);
}
});
secondPlayerPicker = (ImageButton) v.findViewById(R.id.ImageButton01);
secondPlayerPicker.setOnClickListener(new OnClickListener() {
public void onClick(final View v){
callContactPicker(2);
}
});
loadFromFile = (ImageButton) v.findViewById(R.id.imageButton2);
loadFromFile.setOnClickListener(new OnClickListener() {
public void onClick(final View v){
}
});
firstTextfield = (EditText) v.findViewById(R.id.editText1);
secondTextfield = (EditText) v.findViewById(R.id.EditText01);
firstImage = (ImageView) v.findViewById(R.id.imageView1);
secondImage = (ImageView) v.findViewById(R.id.ImageView01);
return v;
}
Ответы
Ответ 1
Вот как я это понял. Я удалил onCreateView и изменил onCreateDialog. Эта ссылка на самом деле имела ответ, поэтому вся заслуга должна идти туда. Я только что опубликовал это на всякий случай, если кто-то столкнется с этим вопросом первым.
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder b= new AlertDialog.Builder(getActivity())
.setTitle("Enter Players")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do something...
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
);
LayoutInflater i = getActivity().getLayoutInflater();
View v = i.inflate(R.layout.doubleplayerchooser,null);
firstPlayerPicker = (ImageButton) v.findViewById(R.id.imageButton1);
firstPlayerPicker.setOnClickListener(new OnClickListener() {
public void onClick(final View v){
callContactPicker(1);
}
});
secondPlayerPicker = (ImageButton) v.findViewById(R.id.ImageButton01);
secondPlayerPicker.setOnClickListener(new OnClickListener() {
public void onClick(final View v){
callContactPicker(2);
}
});
loadFromFile = (ImageButton) v.findViewById(R.id.imageButton2);
loadFromFile.setOnClickListener(new OnClickListener() {
public void onClick(final View v){
}
});
firstTextfield = (EditText) v.findViewById(R.id.editText1);
secondTextfield = (EditText) v.findViewById(R.id.EditText01);
firstImage = (ImageView) v.findViewById(R.id.imageView1);
secondImage = (ImageView) v.findViewById(R.id.ImageView01);
b.setView(v);
return b.create();
}
Ответ 2
Вы должны переопределить метод DialogFragments onCreateDialog (...):
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("title")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do something...
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
Взято отсюда: Android: отключить кнопки OK/Отмена диалога DialogFragment
В соответствии с сообщением об ошибке, которое вы получаете ( "функция запроса должна быть вызвана..." ) Я бы рекомендовал:
Не вызывайте setContentView() перед requestFeature() в своей деятельности или там, где вы его вызываете.
Далее
Не нажимайте setStyle (...) внутри onCreate().
Назовите это, когда вы создадите свой фрагмент.
YourDialogFragment f = new YourDialogFragment(Context);
f.setStyle(...);
// and so on ...
Ответ 3
Чтобы добавить кнопки действий, вызовите setPositiveButton()
и setNegativeButton()
:
public class FireMissilesDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Подробнее о DialogFragment здесь.
Ответ 4
Самый ясный способ.
// Your own onCreate_Dialog_View method
public View onCreateDialogView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.your_layout, container); // inflate here
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// do something with 'view'
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// setup dialog: buttons, title etc
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity())
.setTitle(R.string.dialog_fragment_author_title)
.setNegativeButton(R.string.dialog_fragment_author_close,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
);
// call default fragment methods and set view for dialog
View view = onCreateDialogView(getActivity().getLayoutInflater(), null, null);
onViewCreated(view, null);
dialogBuilder.setView(view);
return dialogBuilder.create();
}
Ответ 5
Это немного устарело, но в последнее время я переопределял onCreateView
при расширении AppCompatDialogFragment
. Просто разместите свои собственные кнопки в том же макете, который вы вернете в onCreateView
- используйте стили, например @style/Widget.AppCompat.Button.Borderless
.
Вы получаете дополнительный бонус для управления самозапусканием Dialog при нажатии кнопки действия, тем более, что эти пользовательские представления иногда имеют требуемые входы, и вы хотите заблокировать автоматическое закрытие диалогового окна при нажатии кнопки.
Использование пользовательского представления в onCreateDialog
всегда считалось грязным, потому что вы раздуваете его без контейнера. Google попытался сделать API немного лучше с новым методом v7 AlertDialog.Builder
setView(int layoutResId)
, но вы не можете вызвать findViewById
, затем.
Вы должны добавить такую тему в свои стили .xml:
<style name="AlertDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="colorPrimary">@color/material_light_blue_500</item>
<item name="colorPrimaryDark">@color/material_light_blue_800</item>
<item name="colorAccent">@color/material_light_blue_a400</item>
<item name="colorButtonNormal">@color/material_light_blue_500</item>
<item name="colorControlNormal">@color/material_light_blue_600</item>
<item name="colorControlActivated">@color/material_light_blue_a100</item>
<item name="colorControlHighlight">@color/material_light_blue_a100</item>
</style>
Вы должны переопределить onCreateDialog
в диалоговом окне DialogFragment, чтобы вернуть new AppCompatDialog(getActivity(), R.style.AlertDialog)
.