如何在AlertDialog中设置正负按钮的顺序?

Mic*_*ine 19 android android-alertdialog

为什么我想这样做完全是另一个讨论,但我需要弄清楚让所有警报对话框在右侧都有正面按钮的最佳方法.请注意,在3.0版及更低版本中,按钮通常显示为"确定/取消",而在4.0及更高版本中则为"取消/确定".我想强制我的应用程序以最简单的方式使用取消/确定.我在应用程序中有很多AlertDialogs.

the*_*ner 17

不幸的是,我不相信你能.但是,引用文档:

注意:您只能将每种按钮类型之一添加到AlertDialog.也就是说,你不能有一个以上的"肯定"按钮.这将可能的按钮数量限制为三个:正面,中性和负面.这些名称在技术上与按钮的实际功能无关,但应该可以帮助您跟踪哪个名称的功能.

因此,您可以将不同的按钮转换为您想要的任何按钮.你现在看到的是具有交换(从点餐,为了这个答案):

  • 在ICS之前的设备上,按钮顺序(从左到右)为POSITIVE - NEUTRAL - NEGATIVE.
  • 在使用ICS的较新设备上,按钮顺序(从左到右)现在为负 - 中性 - 正.

您可以尝试检查Build.VERSION并使用它来确定哪个按钮在运行时.

  • ......现在(6.0)订单是"中立 - - - 否定正面". (6认同)
  • 在4.0.3基于按钮文本的负/正变化的顺序 (3认同)
  • 我在警报对话框和支持警报对话框中看到从左到右的"中性" - "否定" - "正面"顺序.他们改变了主意吗? (2认同)

林奕忠*_*林奕忠 7

这是我的解决方案.这对我有用.

    // Show alertDialog after building
    AlertDialog alertDialog = createAlertDialog(context);
    alertDialog.show();
    // and find positiveButton and negativeButton
    Button positiveButton = (Button) alertDialog.findViewById(android.R.id.button1);
    Button negativeButton = (Button) alertDialog.findViewById(android.R.id.button2);
    // then get their parent ViewGroup
    ViewGroup buttonPanelContainer = (ViewGroup) positiveButton.getParent();
    int positiveButtonIndex = buttonPanelContainer.indexOfChild(positiveButton);
    int negativeButtonIndex = buttonPanelContainer.indexOfChild(negativeButton);
    if (positiveButtonIndex < negativeButtonIndex) {
        // prepare exchange their index in ViewGroup
        buttonPanelContainer.removeView(positiveButton);
        buttonPanelContainer.removeView(negativeButton);
        buttonPanelContainer.addView(negativeButton, positiveButtonIndex);
        buttonPanelContainer.addView(positiveButton, negativeButtonIndex);
    }
Run Code Online (Sandbox Code Playgroud)