亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用以編程方式創建的內容視圖向活動添加片段

如何使用以編程方式創建的內容視圖向活動添加片段

江戶川亂折騰 2019-07-25 16:26:02
如何使用以編程方式創建的內容視圖向活動添加片段我想將一個片段添加到以編程方式實現其布局的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);     }}...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;     }}此代碼編譯但在開始時崩潰,可能是因為我FragmentTransaction.add()的錯誤。這樣做的正確方法是什么?
查看完整描述

3 回答

?
墨色風雨

TA貢獻1853條經驗 獲得超6個贊

這是我在閱讀Tony Wong的評論后想出

public class DebugExampleTwo extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addFragment(android.R.id.content,
                    new DebugExampleTwoFragment(),
                    DebugExampleTwoFragment.FRAGMENT_TAG);
    }}

...

public abstract class BaseActivity extends Activity {

    protected void addFragment(@IdRes int containerViewId,
                               @NonNull Fragment fragment,
                               @NonNull String fragmentTag) {
        getSupportFragmentManager()
                .beginTransaction()
                .add(containerViewId, fragment, fragmentTag)
                .disallowAddToBackStack()
                .commit();
    }

    protected void replaceFragment(@IdRes int containerViewId,
                                   @NonNull Fragment fragment,
                                   @NonNull String fragmentTag,
                                   @Nullable String backStackStateName) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(containerViewId, fragment, fragmentTag)
                .addToBackStack(backStackStateName)
                .commit();
    }}

...

public class DebugExampleTwoFragment extends Fragment {

    public static final String FRAGMENT_TAG = 
        BuildConfig.APPLICATION_ID + ".DEBUG_EXAMPLE_TWO_FRAGMENT_TAG";

    // ...}

科特林

如果您正在使用Kotlin,請務必查看Google提供的Kotlin擴展程序,或者只編寫您自己的擴展程序


查看完整回答
反對 回復 2019-07-25
  • 3 回答
  • 0 關注
  • 434 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號