如何使用以編程方式創建的內容視圖向活動添加片段我想將一個片段添加到以編程方式實現其布局的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擴展程序,或者只編寫您自己的擴展程序。
- 3 回答
- 0 關注
- 434 瀏覽
添加回答
舉報
0/150
提交
取消