我遇到了同样的问题,令我惊讶的是,我找到了解决方案!像这样创建一个空白 XML 布局文件...
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</FrameLayout>
在动态创建布局的片段中,扩充此空白布局 XML 文件。
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.blank_layout, container, false);
return view;
之后,在 onViewCreated() 方法中,您可以动态创建布局。
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// This will create the LinearLayout
LinearLayout ll = new LinearLayout(mContext);
ll.setOrientation(LinearLayout.VERTICAL);
// Configuring the width and height of the linear layout.
LinearLayout.LayoutParams llLP = new LinearLayout.LayoutParams(
//android:layout_width="match_parent" an in xml
LinearLayout.LayoutParams.MATCH_PARENT,
//android:layout_height="wrap_content"
LinearLayout.LayoutParams.MATCH_PARENT);
ll.setLayoutParams(llLP);
TextView tv = new TextView(mContext);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(lp);
//android:text="@string/c4r"
tv.setText("Hello android !");
//android:padding="@dimen/padding_medium"
tv.setPadding(8, 8, 8, 8);
ll.addView(tv);
ViewGroup viewGroup = (ViewGroup) view;
viewGroup.addView(ll);
}
}