我有一项活动。在活动中有一个片段持有者。当应用程序运行时,我显示fragment_1。在fragment_1中,我有一个按钮。当我单击该按钮时,片段持有者将更改为fragment_2。
答案 0 :(得分:0)
试试这个
在Fragment1
创建名为OnFragment1ActiontListener
的公共接口并处理onAttach()
中的逻辑
public class Fragment1 {
OnFragment1ActiontListener mCallback;
// Container Activity must implement this interface
public interface OnFragment1ActiontListener {
public void onSwitchToFragment2();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnFragment1ActiontListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragment1ActiontListener");
}
}
// call this method when you click button
public void onButtonClicked() {
mCallback.onSwitchToFragment2();
}
}
在您的活动中,实施界面OnFragment1ActiontListener
。您需要@Override
以下方法
@Override
public void onSwitchToFragment2() {
// use fragmentholder to change to fragment2
Fragment2 fragment = new Fragment2();
FragmentTransaction trs = getSupportFragmentManager().beginTransaction();
trs.replace(R.id.fragmentholder, fragment);
trs.commit();
}
希望有所帮助!
答案 1 :(得分:0)
// Create new fragment
Fragment newFragment = new NewFragment();
// Open transaction
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();