如何以编程方式创build一个片段的布局?

现在创build片段我做了以下代码。

文件名:fragment_a.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/frag_a" android:layout_width="fill_parent" android:layout_height="fill_parent" > </LinearLayout> 

在Java中

 public class FragA extends Fragment{ View view_a; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view_a = inflater.inflate(R.layout.fragment_a, container, false); return view_a; } } 

现在我需要知道是否有任何方法创build一个片段视图,而不创build一个XML文件,并写入代码?

我想说的是我不想为一个片段创build一个XML文件,而是我想使用Java代码创build该片段的视图。

那可能吗?

Solutions Collecting From Web of "如何以编程方式创build一个片段的布局?"

是的,当然这是可能的。 简单地用例如你的CustomViewreplace膨胀线。

 public class FragA extends Fragment{ View view_a; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view_a = new YourCustomView(); return view_a; } } 

或者像这样:

 public class FragA extends Fragment{ View view_a; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view_a = new LinearLayout(getActivity()); return view_a; } } 

或添加更多视图:

 public class FragA extends Fragment{ View view_a; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LinearLayout ll = new LinearLayout(getActivity()); ll.addView(new TextView(getActivity())); view_a = ll; return view_a; } }