2016-03-11 52 views
1
  1. 我有一个名为DF.java的DialogFragment类,它使用了一个名为DF.xml的基于线性布局的布局。
  2. DF.xml中的子元素(也是linearlayouts)的宽度设置为0dp,并使用权重进行计算。
  3. 我打算在一个按钮上点击一个活动来显示DialogFragment DF,这很好,而且DialogFragment加载正常。

现在,当DialogFragment DF出现时,我需要获取其子元素的一个宽度(线性布局)。getWidth在子视图内DialogFragment

我已经在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,我直接从我的主要活动显示对话框,然后相同的代码在onShow中使用getWidth()完全返回宽度值。

但我真的需要通过DialogFragment为代码组织起见。

任何帮助或指针,我在做什么错在这里将是非常有益的。

回答

0

为了让孩子LinearLayout的宽度在DialogFragment,你可以用getMeasuredWidth()一起使用OnShowListener

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_parentwrap_content

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

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

已经尝试过这一点。我甚至在该子视图(fieldForWidth)的“onclick listener”设置中尝试了这一点。如果我使用TextView在该子视图中添加一些文本,那么我会获得一些宽度,但这只是文本的宽度。 所以我搞清楚的是,当从DialogFragment中创建这个对话框时,宽度不会被测量。 有什么进一步的建议吗? – StackCoder

+0

@StackCoder - 也许问题是由调用“show()”太早造成的?请看看我编辑的答案 - 这次,我在发布前测试了我的建议,至少在Android Studio模拟器(AppCompatActivity,Lollipop) – 0X0nosugar