从Activity的背面按下Android Start Fragment

时间:2016-02-12 06:35:49

标签: android android-fragments android-activity

你好我想在简单活动的背压下开始片段

我这样做了

public boolean onKeyDown(int keyCode, KeyEvent event) {

             Fragment fragment = null;
              fragment = new MainActivity();
             android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
                android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                fragmentTransaction.replace(R.id.content_frame, fragment);



                fragmentTransaction.commit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

但不工作..

2 个答案:

答案 0 :(得分:0)

尝试使用以下代码。

  @Override
    public void onBackPressed() {


 Fragment fragment = null;
              fragment = new MainActivity();
             android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
                android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                fragmentTransaction.replace(R.id.content_frame, fragment);



                fragmentTransaction.commit();
    }

希望它能奏效。

答案 1 :(得分:0)

试试这个:

@Override
public void onBackPressed() {

    android.support.v4.app.FragmentManager mFragmentManager = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
    mFragmentTransaction.replace(R.id.fragmentView, new Fragment()).commit();
}