如何使用以編程方式創(chuàng)建的內(nèi)容視圖向活動(dòng)添加片段我想將一個(gè)片段添加到以編程方式實(shí)現(xiàn)其布局的Activity。我查看了Fragment文檔,但沒有很多示例描述我需要的內(nèi)容。這是我嘗試編寫的代碼類型: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);
}}...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;
}}此代碼編譯但在開始時(shí)崩潰,可能是因?yàn)槲褾ragmentTransaction.add()的錯(cuò)誤。這樣做的正確方法是什么?
如何使用以編程方式創(chuàng)建的內(nèi)容視圖向活動(dòng)添加片段
繁華開滿天機(jī)
2019-07-25 19:32:46