[英]getWidth for a child view within DialogFragment
现在,当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,那么相同的代码使用getWidth()在onShow中完美地返回宽度值。
但是我真的需要通过DialogFragment来实现代码组织。
关于我在这里做错了什么的任何帮助或指示将非常有帮助。
要在DialogFragment
获取子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());
}
});
这适用于宽度设置为match_parent
或wrap_content
的子View
(只是普通View
和LinearLayout
)。
请注意,在我的测试中,我没有在onCreateDialog()
调用CurrentDialog.show()
,而是仅在Activity
代码中使用以下几行来显示该对话框:
DialogFragment mDialog = DF.newInstance("x", "yz");
mDialog.show(getSupportFragmentManager(), "myCurrentDialog");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.