为了更改AlertDialog(support.v7 one)中按钮的对齐方式,已经争论了几个小时,因为它们不会根据区域设置视图的方向对齐,尽管整个应用程序确实向左对齐,AlertDialog中的文本也会对齐
(你说为什么会发生这种情况?我正在用程序将区域设置语言配置为"en",因为这是我的默认应用程序语言,尽管系统区域设置可能是其他语言)。
正如我所说,我不需要触摸对话框中的消息,但作为一个例子,这就是如何改变它的方向:
TextView messageView = (TextView)dialog.findViewById(android.R.id.message);
messageView.setGravity(Gravity.RIGHT); // or LEFT
当然,它对按钮不起作用,因为我需要改变布局的重力。
以下是我如何找到按钮(在我调用AlertDialog.Builder上的show()之后,当然,否则它们将为空):
AppCompatButton accept = (AppCompatButton)dialog.findViewById(android.R.id.button1);
AppCompatButton cancel = (AppCompatButton)dialog.findViewById(android.R.id.button2);
以下是我如何尝试更改它们在父LinearLayout:中的对齐方式
((LinearLayout.LayoutParams)accept.getLayoutParams).gravity = Gravity.RIGHT;
((LinearLayout.LayoutParams)cancel.getLayoutParams).gravity = Gravity.RIGHT;
我选择了RIGHT,因为对话框中按钮的一侧总是与文本对齐的一侧相对。(是-我也尝试了LEFT,没有任何变化)。
这行不通。有人知道如何做到这一点吗?他们似乎只是坚守自己的位置。
编辑:标题也没有对齐,我只是确认了这一点(出于某种原因,它出现在右边,就像我的系统配置,而不是我的区域设置配置)。
问题不在于Gravity
设置。。。当您查看xml源(../sdk/platforms/android-23/data/res/layout/alert_dialog_material.xml
)时,布局的AlertDialog
包含以下内容:
<LinearLayout android:id="@+id/buttonPanel"
style="?attr/buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content" ...>
<Button android:id="@+id/button3"
style="?attr/buttonBarNeutralButtonStyle" ... />
<Space
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1"
android:visibility="invisible" />
<Button android:id="@+id/button2"
style="?attr/buttonBarNegativeButtonStyle" ... />
<Button android:id="@+id/button1"
style="?attr/buttonBarPositiveButtonStyle" ... />
</LinearLayout>
有一个带有按钮的Space
视图。此视图使用容器的重量填充容器。因此,您实际上有一个小部件,它可以按下右侧父容器上的按钮。
一个简单的解决方案可能是获取父级的按钮容器,并在设置重力之前删除Space
元素。
// get the container
LinearLayout containerButtons = (LinearLayout) dialog.findViewById(R.id.buttonPanel);
// remove the Space view
containerButtons.removeView(containerButtons.getChildAt(1));
// set a gravity to the children buttons
containerButtons.setGravity(Gravity.RIGHT);
然而,您应该创建并使用自己的自定义布局,以防未来谷歌的开发可能发生变化。
您可以完全自定义AlertDialog。这里的技巧可能是为对话框使用自定义视图,并在该视图中创建自己的按钮。
有关示例,请参见如何将自定义按钮添加到AlertDialog';s布局?