【问题标题】:Android addToBackStack(null) not working, closing the appAndroid addToBackStack(null) 不工作,关闭应用程序
【发布时间】:2016-05-18 04:32:22
【问题描述】:

在我的应用程序中,我在一个 Activity 中使用 Fragments,我正在尝试替换它们。这很好用,但是在后按时我想切换到上一个片段。我找到了 addToBackStack() 方法,但它不起作用。这是 MainActivity 中的代码:

MainActivity.java:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fragment1 fragment1 = new Fragment1();
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(android.R.id.content, fragment1);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

public void changeFragment(Fragment f)
{
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(android.R.id.content, f);
    fragmentTransaction.commit();
}

@Override
public void onBackPressed()
{
    if (getSupportFragmentManager().getBackStackEntryCount() > 0 )
    {
        getSupportFragmentManager().popBackStackImmediate();
    }
    else
    {
        super.onBackPressed();
    }
}
}

Fragment1.java:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class Fragment1 extends Fragment
{
private Button buttonFragment1;

public Fragment1() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_fragment1, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    buttonFragment1 = (Button)getActivity().findViewById(R.id.buttonFragment1);
    buttonFragment1.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Fragment2 fragment2 = new Fragment2();
            ((MainActivity) getActivity()).changeFragment(fragment2);
        }
    });
}
}

Fragment2.java:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment2 extends Fragment {


public Fragment2()
{
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_fragment2, container, false);
}

}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.asteam.myapplication.MainActivity">

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/fraggment" />
</RelativeLayout>

fragment_fragment1.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.asteam.myapplication.Fragment1">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/buttonFragment1"
        android:text="Send to fragment2"/>

</RelativeLayout>

</FrameLayout>

fragment_fragment2.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.asteam.myapplication.Fragment2">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Fragment2" />

</RelativeLayout>

</FrameLayout>

和清单 xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.asteam.myapplication">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

我试图重写 onBackPressed() 方法:

@Override
public void onBackPressed()
{
    if (getSupportFragmentManager().getBackStackEntryCount() > 0 )
    {
        getSupportFragmentManager().popBackStackImmediate();
    }
    else
    {
        super.onBackPressed();
    }
}

但它不起作用,如果我在单击按钮后显示堆栈号,我会得到 1。我尝试从 android.support.v4. 更改为 android. 到 java 片段文件和主要活动,并将 MainActivity 更改为从 Activity 扩展,但这也不起作用。我究竟做错了什么?我的应用支持 API 14 及更高版本。任何帮助将不胜感激。

已编辑

加上logcat:

02-08 14:38:49.191 10417-10417/? I/art: Not late-enabling -Xcheck:jni (already on)
02-08 14:38:49.266 10417-10417/com.example.asteam.myapplication W/System:  ClassLoader referenced unknown path: /data/app/com.example.asteam.myapplication-2/lib/x86
02-08 14:38:49.322 10417-10432/com.example.asteam.myapplication D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-08 14:38:49.452 10417-10432/com.example.asteam.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
02-08 14:38:49.489 10417-10432/com.example.asteam.myapplication W/EGL_emulation: eglSurfaceAttrib not implemented
02-08 14:38:49.489 10417-10432/com.example.asteam.myapplication W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabebfe80, error=EGL_SUCCESS
02-08 14:38:55.915 10417-10432/com.example.asteam.myapplication E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab852fc0

【问题讨论】:

  • 很高兴你包含了所有这些代码,但是崩溃日志会很完美
  • @ASTeam:尝试在changeFragment 方法中添加fragmentTransaction.addToBackStack(null);

标签: java android xml android-fragments replace


【解决方案1】:

像这样改变你的方法

public void changeFragment(Fragment f)
{
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(android.R.id.content, f);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

那么您应该从onCreateMainActivity 中删除fragmentTransaction.addToBackStack(null);

另外,在Fragment1 中的onActivityCreated 中的代码应该移动到onCreateView

【讨论】:

  • 更改后,如果我在单击按钮后按回,它会返回,但如果我再次单击该按钮,它不会做任何事情,如果我继续单击它会导致应用程序崩溃:java .lang.NullPointerException:尝试在 com.example.asteam.myapplication.Fragment1 的空对象引用上调用虚拟方法 'void com.example.asteam.myapplication.MainActivity.changeFragment(android.support.v4.app.Fragment)' $1.onClick(Fragment1.java:38)
  • 您应该从onCreate of MainActivity 中删除fragmentTransaction.addToBackStack(null);
  • 它在第一次按下后仍然“禁用”按钮,所以我不能再进入片段 2,但它不会再让应用程序崩溃......
  • Fragment1里面的onActivityCreated代码应该移动到onCreateView
  • 我试过了,因为每次按下返回按钮和 Activity 时都会创建片段,所以 onclick() 方法不再与按钮相关,谢谢。但是在尝试 changeFragment(Fragment f) 方法时,我使用了 fragmentTransaction.add(android.R.id.content, f) 而不是 replace() 并且它也有效。哪个更好?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多