问题描述
我将使用对话片段。
writing_comment_item.xml
中有一个名为 dialogfragment
的项目,我想设置 height
项目的 5
。
我使用了 inflate() 函数,我使用了 getHeight()
来获取布局。
但是经过调试,高度是0
。
我在 onCreate()
中尝试过。也试过 onCreateView()
。
结果是一样的
我该怎么办?
writing_comment_item.xml
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".fragment.WritingCommentDialogFragment">
<EditText
android:id="@+id/comment_edit"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:gravity="center_vertical"
android:drawableLeft="@drawable/ic_bullet_point"
android:drawablePadding="5dp"
android:layout_marginHorizontal="10dp"
android:background="@null"
android:textSize="15sp"
android:inputType="text"
android:maxLines="1"
android:maxLength="22"
android:imeOptions="actionNext"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
</EditText>
</androidx.constraintlayout.widget.ConstraintLayout>
WCDialogFragment.java
public class WritingCommentDialogFragment extends DialogFragment implements CommentModel.EditInputListener {
OnBackpressedCallback callback;
LinearLayout commentContainer; // input layout
private final List<Comment> comments = new ArrayList<>();
private LayoutInflater layoutInflater;
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_writing_comment_dialog,container,false);
bindViews(view);
addCommentItem();
return view;
}
private void bindViews(View v) {
commentContainer = v.findViewById(R.id.container);
layoutInflater = LayoutInflater.from(getContext());
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
@Override
public void onResume() {
super.onResume();
setDialogSize();
}
private void setDialogSize() {
View v = LayoutInflater.from(getContext()).inflate(R.layout.writing_comment_item,null,false);
int h = v.getHeight() * 5;
getDialog().getwindow().setLayout(1000,h);
}
}
已编辑
private void setDialogSize() {
View v = LayoutInflater.from(getContext()).inflate(R.layout.writing_comment_item,false);
v.measure(View.MeasureSpec.UNSPECIFIED,View.MeasureSpec.UNSPECIFIED);
v.getMeasuredHeight();
int h = v.getMeasuredHeight() * 5;
getDialog().getwindow().setLayout(1000,h);
}
解决方法
这里的错误是试图获取尚未添加到布局层次结构中的视图的高度。当你打电话
inflate(R.layout.writing_comment_item,null,false);
当 attachToRoot
为 false
时,您指定不希望将其添加到层次结构中,因此系统永远不会测量视图。
您可以改为自己调用 View.measure(int,int)
,然后使用 View.getMeasuredHeight()
。这个问题更详细地介绍了这一点 - Measuring a view before rendering it