为什么onBackPressed会杀死我的应用?

时间:2016-03-11 19:19:59

标签: android android-fragments back-stack fragment-backstack

当我开始研究这个时,我使用的是mapbox android api而不是google maps api。我认为这不会对出现什么问题产生太大影响但是,我确实在某种程度上支持了背包。

就像现在一样,我可以一直到我的视频播放器片段。 (靠背上的第3个)。如果我从那里点击后退按钮,将显示回收器视图,然后应用程序将从屏幕上消失。如果我从地图转到回收者视图,然后点击背压 - 地图将显示,然后立即从屏幕上消失。

如果我还有其他任何可以发布的信息,请告诉我。

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback, FragmentManager.OnBackStackChangedListener {


FragmentManager fragmentManager = getFragmentManager();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


    fragmentManager.addOnBackStackChangedListener(this);

    FragmentTransaction ft = fragmentManager.beginTransaction();
    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
    ft.addToBackStack("Main Fragment");
    ft.commit();

    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {

    LatLng sydney = new LatLng(-33.867, 151.206);

    map.setMyLocationEnabled(true);
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));

    map.addMarker(new MarkerOptions()
            .title("Sydney")
            .snippet("The most populous city in Australia.")
            .position(sydney));
}



@Override
public void onBackPressed() {

    if (fragmentManager.getBackStackEntryCount() != 0) {
        fragmentManager.popBackStackImmediate();
    }else {
        super.onBackPressed();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    String title = item.getTitle().toString();



    if (title.equals("Topic One")) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        RecyclerViewFragment rvs = new RecyclerViewFragment().newInstance(0);
        ft.setCustomAnimations(R.animator.top_to_bottom_fragment, android.R.animator.fade_out);
        ft.replace(R.id.map, rvs, "subject_cards");
        ft.addToBackStack("Topic One");
        ft.commit();


    } else if (title.equals("Topic Two")) {

        FragmentTransaction ft = getFragmentManager().beginTransaction();
        RecyclerViewFragment rvs = new RecyclerViewFragment().newInstance(1);
        ft.replace(R.id.map, rvs, "subject_cards");
        ft.addToBackStack("Topic Two");
        ft.commit();

    } 
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

    return true;
}


@Override
public void onStart() {
    super.onStart();

}

@Override
public void onResume() {
    super.onResume();
}



@Override
public void onPause()  {
    super.onPause();
}

@Override
public void onStop() {
    super.onStop();
}




@Override
public void onBackStackChanged() {
    FragmentManager fm = getFragmentManager();
    int bsCOunt = fm.getBackStackEntryCount();

    for(int i = 0; i < bsCOunt; i++){

        System.out.println( "Fragment name:  " + fm.getBackStackEntryAt(i).getName() +"\n");
        System.out.println("");
    }


}
}

RecyclerViewFragment:

public class RecyclerViewFragment extends Fragment {
private List<Subject> subjects;
static RecyclerView rv;
static int cardViewPosition;


View rootView;
private static final String TAG = "RECYCLER_VIEW_FRAGMENT";

public static RecyclerViewFragment newInstance(int some_Int) {
    RecyclerViewFragment frag = new RecyclerViewFragment();
    Bundle args = new Bundle();
    args.putInt("card_int", some_Int);
    frag.setArguments(args);
    return frag;
}



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    cardViewPosition = getArguments().getInt("card_int", 0);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.recyclerview_activity, container, false);
    rootView.setTag(TAG);
    rv = (RecyclerView) rootView.findViewById(R.id.rv);
    final LinearLayoutManager llm = new LinearLayoutManager(getActivity());
    rv.setLayoutManager(llm);
    rv.setHasFixedSize(true);
    rv.scrollToPosition(cardViewPosition);
    initializeData();
    initializeAdapter();
    return rootView;

}




private void initializeData() {
    subjects = new ArrayList<>();
    JSONObject obj;
    JSONArray jArray = null;
    try {
        obj = new JSONObject(loadJsonFromAsset());
        jArray = obj.getJSONArray("people");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < jArray.length(); i++) {
        JSONObject json_data = null;

        try {
            json_data = jArray.getJSONObject(i);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            subjects.add(new Subject(json_data.getInt("id"), json_data.getString("name"), null,
                    null, getResources().getIdentifier(json_data.getString("photoId"), "drawable",
                    this.getActivity().getPackageName()), json_data.getString("subjectText"),json_data.getString("expandedSubjectText")));

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}


private void initializeAdapter() {


    RVAdapter adapter = new RVAdapter(subjects,rootView.getContext());

    adapter.setOnClickListener(new RVAdapter.MyListener() {

        @Override
        public void onClick(View v, int i, CharSequence subjectName) {

            if (v.equals(v.findViewById(R.id.card_button_left))) {

                rv.scrollToPosition(i);

                FragmentTransaction ft = getFragmentManager().beginTransaction();

                VideoPlayerFragment vFrag = new VideoPlayerFragment().newInstance(subjectName);
                ft.setCustomAnimations(R.animator.top_to_bottom_fragment, android.R.animator.fade_out);
                ft.replace(android.R.id.content, vFrag);
                ft.addToBackStack(null);
                ft.commit();

                FragmentManager fragmentManager = getFragmentManager();



            }else if(v.equals(v.findViewById(R.id.card_button_right))){
                rv.scrollToPosition(i);
            }
        }
    });

    rv.setAdapter(adapter);
}


public String loadJsonFromAsset() {
    String json = null;
    InputStream is = getResources().openRawResource(R.raw.people);
    try {
        int size = is.available();

        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return json;
}

}

视频播放器片段:

public class VideoPlayerFragment extends Fragment {

private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
WebView videoDisplay = null;
static CharSequence subjectName;
static String htmlPageForSubject;
CharSequence title;
CharSequence openingText;
CharSequence mainText;
CharSequence[] text;


public static VideoPlayerFragment newInstance(CharSequence subjectName) {
    VideoPlayerFragment vFrag = new VideoPlayerFragment();
    Bundle arg = new Bundle();
    arg.putCharSequence("subject_name", subjectName);
    vFrag.setArguments(arg);
    return vFrag;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.subjectName = getArguments().getCharSequence("subject_name");
    htmlPageForSubject = subjectName.toString().replace(' ', '_');
    PeopleReader peopleReader = new PeopleReader(subjectName);
    text = peopleReader.fetchText();
    title = text[0];
    openingText = text[1];
    mainText = text[2];

}


@Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) {


    View rootView = layoutInflater.inflate(R.layout.webview_layout, container, false);

    videoDisplay = (WebView) rootView.findViewById(R.id.webView);
    TextView firstTextBox = (TextView) rootView.findViewById(R.id.titleText);
    TextView secondTextBox = (TextView) rootView.findViewById(R.id.openingText);
    TextView thirdTextBox = (TextView) rootView.findViewById(R.id.mainText);

    firstTextBox.setText(title);
    secondTextBox.setText(openingText);
    thirdTextBox.setText(mainText);

    videoDisplay.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }
    });

    WebSettings webSettings = videoDisplay.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    videoDisplay.loadUrl("file:///android_asset/www/" + htmlPageForSubject + ".html");

    videoDisplay.setWebChromeClient(new MyWebChromeClient());


    return rootView;
}



public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}

class MyWebChromeClient extends WebChromeClient {

    private int mOriginalSystemUiVisibility;
    private int mOriginalOrientation;

    @Override
    public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        if (mCustomView != null) {
            onHideCustomView();
            return;
        }

        mCustomView = view;
        mOriginalSystemUiVisibility = getActivity().getWindow().getDecorView().getSystemUiVisibility();
        mOriginalOrientation = getActivity().getRequestedOrientation();

        mCustomViewCallback = callback;

        FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
        decor.addView(mCustomView, new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));

        getActivity().getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                        View.SYSTEM_UI_FLAG_FULLSCREEN |
                        View.SYSTEM_UI_FLAG_IMMERSIVE);
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    @Override
    public void onHideCustomView() {
        // 1. Remove the custom view
        FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
        decor.removeView(mCustomView);
        mCustomView = null;

        getActivity().getWindow().getDecorView()
                .setSystemUiVisibility(mOriginalSystemUiVisibility);
        getActivity().setRequestedOrientation(mOriginalOrientation);

        mCustomViewCallback.onCustomViewHidden();
        mCustomViewCallback = null;

    }

}


class PeopleReader {

    CharSequence topicName;
    CharSequence[] textArray = new String[3];

    public PeopleReader(CharSequence topicName){

        this.topicName = topicName;

    }

    public CharSequence[] fetchText() {

        JSONObject obj;
        JSONArray jArray = null;

        try {
            obj = new JSONObject(loadJsonFromAsset());
            jArray = obj.getJSONArray("people");
        } catch (JSONException e1) {
            e1.printStackTrace();
        }


        for(int i = 0;i<jArray.length();i++){

            JSONObject json_data;

            try {
                json_data = jArray.getJSONObject(i);

                if(json_data.getString("name").equals(topicName.toString())){

                    textArray[0] = json_data.getString("name");
                    textArray[1] = json_data.getString("subjectText");
                    textArray[2] = json_data.getString("expandedSubjectText");

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return textArray;
    }

    public String loadJsonFromAsset() {
        String json = null;
        InputStream is = getResources().openRawResource(R.raw.people);
        try {
            int size = is.available();

            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

}

}

2 个答案:

答案 0 :(得分:2)

只要您的抽屉没有打开,您就会使用默认的super.onBackPressed()行为。试试这个。

@Override
public void onBackPressed() {

    if (fragmentManager.getBackStackEntryCount() != 0) {
        fragmentManager.popBackStackImmediate();
        return;
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
        return;
    }

    // Otherwise defer to system default behavior.
    super.onBackPressed();

}

答案 1 :(得分:0)

如果没有任何回复,super.onBackPressed();将退出应用。您当然可以通过删除该行来消除此行为,但我强烈建议不要这样做。

您可能会考虑弹出AlertDialog以确认用户是否要退出。或者,你可以打印一个Toast说“再次击退将退出应用程序”并处理该行为。