我想以編程方式和動態構建整個片段佈局。所以我創造了這個代碼:無法將視圖添加到片段中的嵌套線性佈局
@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