在运行时添加 Fragment,在运行时设置其布局,Android 中不涉及布局 xml 个文件

Add Fragment at Runtime, set its layout at runtime, no layout xml files involved in Android

我有一个 activity 可以在 onCreate 中动态创建其布局。它看起来像这样:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /*
     laying out screen at runtime (activity_main.xml is not used).
     */
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, 
            100);
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);

    // instantiate my class that does drawing on Canvas
    bubble = new Bubble(this);
    bubble .setLayoutParams(lp);
    bubble .setBackgroundColor(MY_COLOR);
    ll.addView(bubble);
    setContentView(ll);
}

所以,根本就没有布局,这就是它应该保留的样子。

我想添加片段而不是上面的代码,然后作为片段 onCreate() 的一部分,实例化我的泡泡 class 进行绘图。该片段也不应该在布局 XML 文件中定义任何布局,但它应该都在运行时。

非常感谢,

重新编写代码以使用 Fragments 非常简单。将 View 声明移至 Fragment,将实例移至其 onCreateView() 方法,并将 return 父 ViewGroup 移至。例如:

public class BubbleFragment extends Fragment
{
    Bubble bubble;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        /*
         laying out screen at runtime (activity_main.xml is not used).
         */
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, 
            100);
        LinearLayout ll = new LinearLayout(getActivity());
        ll.setOrientation(LinearLayout.VERTICAL);

        // instantiate my class that does drawing on Canvas
        bubble = new Bubble(getActivity());
        bubble.setLayoutParams(lp);
        bubble.setBackgroundColor(MY_COLOR);
        ll.addView(bubble);

        return ll;
    }
}

请注意,View 的构造函数参数已更改为 getActivity(),因为 Fragment 不是 Context。此外,如果不再向 Fragment 添加 View,您可以省略 LinearLayout,只 return Bubble 对象。

Activity 需要自己的布局,包括 ViewGroup - 通常是 FrameLayout - 来容纳 Fragment。无论您是使用预定义的 XML 布局还是动态生成它都没有关系。您只需要 ViewGroup 的 ID,即可将其传递给 FragmentTransaction#add() 方法之一。例如:

BubbleFragment keplerFragment = new BubbleFragment(...);
getFragmentManager().beginTransaction().add(R.id.content, keplerFragment, TAG_KEPLER_FRAGMENT);

并且,如评论中所述,自 AppCompatActivity extends FragmentActivity 以来,您无需更改 Activity 的超类。