相关疑难解决方法(0)

如何使用以编程方式创建的内容视图向活动添加片段

我想将一个片段添加到以编程方式实现其布局的Activity.我查看了Fragment文档,但没有很多示例描述我需要的内容.这是我尝试编写的代码类型:

public class DebugExampleTwo extends Activity {

    private ExampleTwoFragment mFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FrameLayout frame = new FrameLayout(this);
        if (savedInstanceState == null) {
            mFragment = new ExampleTwoFragment();
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.add(frame.getId(), mFragment).commit();
        }

        setContentView(frame);
    }
}
Run Code Online (Sandbox Code Playgroud)

...

public class ExampleTwoFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, 
                             ViewGroup container, 
                             Bundle savedInstanceState) {
        Button button = new Button(getActivity());
        button.setText("Hello There");
        return button;
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码编译但在开始时崩溃,可能是因为我FragmentTransaction.add()的错误.这样做的正确方法是什么?

android android-fragments android-3.0-honeycomb

224
推荐指数
8
解决办法
42万
查看次数