现在,当DialogFragment DF显示时,我需要获取其子元素之一的宽度(线性布局)。
我在onCreateDialog中尝试了getWidth,getMeaseuredWidth,ViewTreeObserver等,但结果始终为零。
显示DialogFragment的代码
DF dialog = DF.newInstance(context, "DFInstance");
dialog.show(((Activity)context).getFragmentManager(), "DFInstance");
DialogFragment DF.java类中的代码
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = LayoutInflater.from(context);
View dialog_layout = inflater.inflate(R.layout.dialog_DF,
null);
CurrentDialog = new Dialog(context, R.style.DFTheme);
CurrentDialog.setCanceledOnTouchOutside(true);
CurrentDialog.setContentView(dialog_layout);
CurrentDialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
CurrentDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
//Tried getting width here using many approaches, Ex:
int Width1 = (((Dialog)dialog).findViewById(R.Id.fieldForWidth)).getWidth();
// Also tried using MeasureSpec here and then getMeasuresWidth
// Also tried adding above code in ViewTreeObserver here.
}
});
Window window = CurrentDialog.getWindow();
window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
CurrentDialog.show();
return CurrentDialog;
}
但奇怪的是,如果我选择反对DialogFragment,并且我直接从我的主活动中显示Dialog,那么相同的代码在onShow中使用getWidth()完美地返回宽度值。
但为了代码组织,我真的需要通过DialogFragment这样做。
关于我在这里做错了什么的任何帮助或指示都会非常有帮助。
答案 0 :(得分:0)
要获得LinearLayout
中孩子DialogFragment
的宽度,您可以OnShowListener
与getMeasuredWidth()
一起使用
final int width;
myDialog.setOnShowListener(new DialogInterface.OnShowListener()
{
@Override
public void onShow(DialogInterface dialog)
{
width = ((Dialog)dialog).findViewById(R.id.field_for_width).getMeasuredWidth());
}
});
这适用于宽度设置为View
或View
的儿童LinearLayout
(只是普通match_parent
以及wrap_content
)。
请注意,在我的测试中,我没有在CurrentDialog.show()
中致电onCreateDialog()
但只使用Activity
代码中的以下行来显示对话框:
DialogFragment mDialog = DF.newInstance("x", "yz");
mDialog.show(getSupportFragmentManager(), "myCurrentDialog");