- 我有一個名爲DF.java的DialogFragment類,它使用了一個名爲DF.xml的基於線性佈局的佈局。
- DF.xml中的子元素(也是linearlayouts)的寬度設置爲0dp,並使用權重進行計算。
- 我打算在一個按鈕上點擊一個活動來顯示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爲代碼組織起見。
任何幫助或指針,我在做什麼錯在這裏將是非常有益的。
已經嘗試過這一點。我甚至在該子視圖(fieldForWidth)的「onclick listener」設置中嘗試了這一點。如果我使用TextView在該子視圖中添加一些文本,那麼我會獲得一些寬度,但這只是文本的寬度。 所以我搞清楚的是,當從DialogFragment中創建這個對話框時,寬度不會被測量。 有什麼進一步的建議嗎? – StackCoder
@StackCoder - 也許問題是由調用「show()」太早造成的?請看看我編輯的答案 - 這次,我在發佈前測試了我的建議,至少在Android Studio模擬器(AppCompatActivity,Lollipop) – 0X0nosugar