我正在尝试向 Fragment 动态添加多个视图:
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
ViewGroup vg = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
ViewGroup parent = (ViewGroup) getActivity().findViewById(R.id.linearLayoutOfFirstFragment);
if (parent==null)
Toast.makeText(getActivity(),
"Null object " ,
Toast.LENGTH_SHORT).show(); //findViewById(R.id.linearLayoutOfFirstFragment);
myFirstView= (TextView)inflater.inflate(R.layout.mytextview, container, false);
vg.addView(myFirstView);
/*mySecondView= (TextView)inflater.inflate(R.layout.mytextview, container, false);
parent.addView(mySecondView);
……
片段 1 的 XML - fragment1.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:id="@+id/linearLayoutOfFirstFragment"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#00FF00"/>
</ScrollView>
当顶部布局是线性布局时,我可以将它添加到片段中。但是,当尝试在膨胀后将其添加到滚动视图内的线性布局时,得到线性布局对象 NULL。我也应该膨胀线性布局,以便能够添加到它吗?怎么做?先感谢您。