繁体   English   中英

DialogFragment中子视图的getWidth

[英]getWidth for a child view within DialogFragment

  1. 我有一个名为DF.java的DialogFragment类,它使用基于线性布局的名为DF.xml的布局。
  2. DF.xml中的子元素(再次为linearlayouts)的宽度设置为0dp,并使用权重计算。
  3. 我计划通过单击按钮显示一个活动的DialogFragment DF,它工作正常,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获取子LinearLayoutDialogFragment ,可以将OnShowListenergetMeasuredWidth()一起使用:

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_parentwrap_content的子View (只是普通ViewLinearLayout )。

请注意,在我的测试中,我没有在onCreateDialog()调用CurrentDialog.show() ,而是仅在Activity代码中使用以下几行来显示该对话框:

DialogFragment mDialog = DF.newInstance("x", "yz");
mDialog.show(getSupportFragmentManager(), "myCurrentDialog");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM