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

时间:2015-10-12 23:04:56

标签: android fragment

我有一个在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()的一部分,实例化我的Bubble类来做绘图。该片段也不应该在布局XML文件中定义任何布局,但它应该都在运行时。

非常感谢,

1 个答案:

答案 0 :(得分:1)

重新编写代码以使用Fragment非常简单。将View声明移至Fragment,将实例移至其onCreateView()方法,然后返回父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 s'构造函数'参数已更改为getActivity(),因为Fragment不是Context。此外,如果不再向View添加Fragment,您可以省略LinearLayout,只返回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的超类。