【发布时间】:2016-01-15 21:42:55
【问题描述】:
我有一个名为 A 的活动。该活动有 1 个框架布局,其中使用了片段。我有两个片段,片段 1 和片段 2。当 Activity 启动时,Fragment 1 填充 Frame Layout。
Fragment1 还包含一个按钮,当单击该按钮时,该按钮将在同一个框架布局中将其替换为 Fragment2。我的问题是,当我单击 Fragment1 中的那个按钮时,我应该实现该代码以便
A) Activity A 通过使用某种类型的布尔值的接口收到 Fragment 中的 onClick 通知,然后继续用 Fragment2 替换它。
或
B)在Fragment1自身内实现将Fragment1替换为Fragment2的代码 例如:
private FragmentTransaction ft;
private Button registerButton, resetButton;
private Fragment fragment;
public LoginFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login, container, false);
registerButton = (Button)view.findViewById(R.id.register_button);
resetButton = (Button) view.findViewById(R.id.reset_button);
registerButton.setOnClickListener(this);
resetButton.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.register_button: {
fragment = new RegisterFragment();
ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
break;
}
}
}
有人能解释一下为什么会这样吗?非常感谢!
【问题讨论】:
-
I have one Activity Called A. The activity has 1 Frame Layout in which Fragments are used. I have two Fragments, Fragment1 and Fragment2. When the Activity is launched, Fragment 1 fills the Frame Layout. Fragment1 also contains a button that when clicked replaces it with Fragment2 within that same Frame Layout. My question is this, when I click that Button in Fragment1 should I implement that code so that能否将此代码添加到您的问题中 -
我会选择选项 A,因为 Fragment 本身不应该知道它的状态,即控制 Activity 的 FragmentManager
-
好的,谢谢,我添加了选项B的代码示例