如何从2_nd,3_rd片段返回起始片段?

时间:2015-03-06 14:58:48

标签: android android-fragments fragmenttransaction

这是我的代码 我需要从A-> B-> C和B和C的onBackPressed()转到A 按下它然后转到B然后转到C,在我看来,transaction.addToBackStack(null);不按需使用

public class TestfragmentActivity extends FragmentActivity{
private FrameLayout layout;
private String TAG = "TAG";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test_fragment);
    layout = (FrameLayout) findViewById(R.id.container);
    A fragment = new A();
    doFragmentTransaction(fragment, false);
}

private void doFragmentTransaction(Fragment fragment, boolean addToBackstack) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.container, fragment);
    if (addToBackstack)
        transaction.addToBackStack(TAG);
    transaction.commit();
}
///////////////
public class A extends Fragment {
private Button button;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.test_fragment1, null);
    button = (Button) view.findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            B fragment = new B();
            doFragmentTransaction(fragment, true);
        }
    });

    return view;
}


private void doFragmentTransaction(Fragment fragment, boolean addToBackstack) {
    FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.container, fragment);

    if (addToBackstack) {
        transaction.addToBackStack(null);
    }

    transaction.commit();
}



//////////////////////


public class B extends Fragment {
private Button button;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.test_fragment2, null);
    button = (Button) view.findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            C fragment = new C();
            doFragmentTransaction(fragment, false);
        }
    });

    return view;
}

private void doFragmentTransaction(Fragment fragment, boolean addToBackstack) {
    FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();

    transaction.replace(R.id.container, fragment);

    if (addToBackstack)
        transaction.addToBackStack(null);

    transaction.commit();
}

} }

1 个答案:

答案 0 :(得分:0)

在片段B和C中,

    @Override
    public void onBackPressed() {

    }

在函数中,用Fragment A替换Container。