DialogFragment中子视图的getWidth

时间:2016-03-11 11:38:37

标签: java android android-layout android-dialogfragment

  1. 我有一个名为DF.java的DialogFragment类,它使用名为DF.xml的基于linearlayout的布局。
  2. DF.xml中的子元素(再次为linearlayouts)的宽度设置为0dp,并使用权重计算。
  3. 我计划通过单击按钮显示活动中的DialogFragment DF,该工作正常,DialogFragment加载正常。
  4. 现在,当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这样做。

    关于我在这里做错了什么的任何帮助或指示都会非常有帮助。

1 个答案:

答案 0 :(得分:0)

要获得LinearLayout中孩子DialogFragment的宽度,您可以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());

        }
    });

这适用于宽度设置为ViewView的儿童LinearLayout(只是普通match_parent以及wrap_content)。

请注意,在我的测试中,我没有在CurrentDialog.show()中致电onCreateDialog()但只使用Activity代码中的以下行来显示对话框:

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