在学习Android Programming:The Big Nerd Ranch的时候,里面有一个challenge,就是在修改日期时需要首先设定日期修改类型,即用户需选择是修改日期还是修改时间,具体实现过程就不说了,这里单说一下在做日期修改类型对话框时遇到的关于布局的一个问题。
首先列出日期修改类型对话框布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dateUpdateChoiceRg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/updateDateRadio"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_weight="1"
android:checked="true"
android:gravity="center_vertical|start"
android:text="@string/date_update_date" />
<RadioButton
android:id="@+id/updateTimeRadio"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_weight="1"
android:text="@string/date_update_time" />
</RadioGroup>
日期修改类型对话框显示如下:
很明显,RadioGroup(背景为绿色)看起来并没有居中显示,下面有空白。经过HeirarchyViewer分析之后,发现 RadioGroup的parent,一个id为android.R.id.custom的FrameLayout,并没有占据全部的可用区域,所以需要修改DialogFragment中onCreateDialog方法的代码,给创建的dialog注册onShow事件监听器,在这个事件监听器中改变 RadioGroup容器的布局属性,代码如下(result是一个Dialog对象):
result.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface arg0) {
FrameLayout customLayout = (FrameLayout) result
.findViewById(android.R.id.custom);
if (customLayout != null) {
customLayout.setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, 0x11));
}
}
});
修改之后日期修改类型对话框如下: