我正在尝试动态地向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。 我是否应该对线性布局进行充气,以便能够添加?怎么做? 先感谢您。
答案 0 :(得分:1)
更改
ViewGroup vg = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
ViewGroup parent = (ViewGroup) getActivity().findViewById(R.id.linearLayoutOfFirstFragment);
带
ViewGroup vg = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
ViewGroup parent = (ViewGroup) vg.findViewById(R.id.linearLayoutOfFirstFragment);
由于linearLayoutOfFirstFragment位于fragment1内,您必须通过vg检索它