我想以编程方式和动态构建整个片段布局。所以我创造了这个代码:无法将视图添加到片段中的嵌套线性布局
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.empty_container, container, false);
final FrameLayout rootView = (FrameLayout) view.findViewById(R.id.empty_container);
final LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setBackgroundColor(Color.BLACK);
rootView.addView(linearLayout);
final Button button = new Button(getActivity());
button.setBackgroundColor(Color.GREEN);
button.setText("button name");
button.setLayoutParams(new LinearLayout.LayoutParams(100, 100));
linearLayout.addView(button);
return view;
}
和XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="@+id/empty_container"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
我无法弄清楚,为什么这不能正常工作。按钮根本不可见(但线性布局是可见的 - 整个屏幕是黑色的)。当我将其中一个按钮布局参数设置为MATCH_PARENT
它突然出现,但是当我将它设置为100像素或WRAP_CONTENT
它没有显示。
打开Android设备监控,运行应用程序,然后与树查看器查看您的DOM。您将能够看到视图是否被添加到您的DOM。 –
http://developer.android.com/tools/help/hierarchy-viewer.html –
使用层次结构查看器我发现按钮被隐藏在工具栏下,谢谢@RussellElfenbein – tymbark