当我按下片段(PreferenceFragment)时 - 应用程序关闭

时间:2016-04-03 17:27:20

标签: android android-fragments

我有导航抽屉的应用程序。它由两个项目组成:Main和Settings。所有项目都是碎片。 "设置"扩展PreferenceFragment。

我有问题。当我启动应用程序时 - 打开MainFragment。他们切换到PreferencesFragment,然后按Back。在这种情况下,我的应用必须切换到MainFragment,但App已关闭。

MainActivity

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.egoriku.lesson_16.R;
import com.egoriku.lesson_16.adapters.ClassAdapter;
import com.egoriku.lesson_16.adapters.DataAdapter;
import com.egoriku.lesson_16.fragments.MainFragment;
import com.egoriku.lesson_16.fragments.PreferencesFragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

private Toolbar toolbar;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private ListView drawerListView;
private List<DataAdapter> list;
private ClassAdapter adapter;


public static final String TAG_MAIN = "TAG_MAIN";
public static final String TAG_SETTING = "TAG_SETTING";

private String itemDrawerMain;
private String itemDrawerSettings;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.e("onCreate", "start");

    itemDrawerMain = getString(R.string.item_drawer_main);
    itemDrawerSettings = getString(R.string.item_drawer_settings);

    drawerLayout = (DrawerLayout) findViewById(R.id.draver_layout);
    toolbar = (Toolbar) findViewById(R.id.toolbar);

    drawerListView = (ListView) findViewById(R.id.nav_list);
    drawerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    list = new ArrayList<>();
    AddMenuItem(list);

    drawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String tag = list.get(position).getTagFragment();

            if (tag.equals(MainFragment.TAG_MAINFRAGMENT)) {
                showFragment(
                        MainFragment.newInstance(),
                        MainFragment.TAG_MAINFRAGMENT,
                        null,
                        true
                );
                drawerLayout.closeDrawers();
            }

            if (tag.equals(PreferencesFragment.TAG_PREFERENCE)) {
                showFragment (
                        PreferencesFragment.newInstanse(),
                        PreferencesFragment.TAG_PREFERENCE,
                        MainFragment.TAG_MAINFRAGMENT,
                        false
                );
                drawerLayout.closeDrawers();
            }
        }
    });

    setSupportActionBar(toolbar);
    drawerToggle = new ActionBarDrawerToggle(
            this,
            drawerLayout,
            toolbar,
            R.string.drawer_open,
            R.string.drawer_close
    );

    drawerLayout.addDrawerListener(drawerToggle);

    if (savedInstanceState == null) {
        Log.e("savedInstanceState", "start");

        showFragment(MainFragment.newInstance(), MainFragment.TAG_MAINFRAGMENT, null, true);
    }
}

private void AddMenuItem(List<DataAdapter> list) {
    Log.e("AddMenuItem", "start");
    list.add(new DataAdapter(itemDrawerMain, R.drawable.ic_main_black, MainFragment.TAG_MAINFRAGMENT));
    list.add(new DataAdapter(itemDrawerSettings, R.drawable.ic_setting_black, PreferencesFragment.TAG_PREFERENCE));
    drawerListView.setAdapter(new ClassAdapter(list, this));
}

//функция для переключения фрагментом
private void showFragment(
        Fragment fragment,
        String tag,
        String clearToTag,
        boolean clearInclusive
) {
    Log.e("showFragment", "start");

    FragmentManager fragmentManager = getFragmentManager();

    if (clearToTag != null || clearInclusive) {
        fragmentManager.popBackStack(
                clearToTag,
                clearInclusive ? FragmentManager.POP_BACK_STACK_INCLUSIVE : 0
        );
    }

    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.replace(R.id.fragment_container, fragment, tag);
    transaction.addToBackStack(tag);
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    transaction.commit();
}

//нужен для drawer toggle
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
    Log.e("onPostCreate", "start");
    super.onPostCreate(savedInstanceState);
    drawerToggle.syncState();
}

//нужен для drawer toggle
@Override
public void onConfigurationChanged(Configuration newConfig) {
    Log.e("onConfigurationChanged", "start");
    super.onConfigurationChanged(newConfig);
    drawerToggle.onConfigurationChanged(newConfig);
}

//нужен для drawer toggle
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Log.e("onOptionsItemSelected", "start");
    return drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}

//нужно для хорошего UX
@Override
public void onBackPressed() {
    if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
        drawerLayout.closeDrawer(GravityCompat.START);
        Log.e("onBask", "start");
        return;
    }

    Log.e("onback", String.valueOf(getFragmentManager().getBackStackEntryCount()));
    if (getFragmentManager().getBackStackEntryCount() == 1) {
        finish();
        Log.e("onBask", "count");
        return;
    }
    super.onBackPressed();
}
}

MainFragment

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.egoriku.lesson_16.R;
import com.egoriku.lesson_16.activities.ResultActivity;

public class MainFragment extends Fragment {
    public MainFragment() {
    }

    public static final String TAG_MAINFRAGMENT = "TAG_MAINFRAGMENT";

    public static MainFragment newInstance() {
        return new MainFragment();
    }

    private Button btnGetResult;
    private EditText editText;

    @Override
    public void onStart() {
        super.onStart();
        getActivity().setTitle(R.string.app_name);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_main, container, false);

        btnGetResult = (Button) v.findViewById(R.id.main_fragment_btn);
        editText = (EditText) v.findViewById(R.id.main_fragment_edit_text);

        btnGetResult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), ResultActivity.class)
                                .putExtra(ResultActivity.EXTRA_EDIT_TEXT, editText.getText().toString())
                );
            }
        });

        return v;
    }
}

2 个答案:

答案 0 :(得分:2)

当然,应用程序将关闭,因为您基本上只有1个Activity,您可以在其中切换两个不同的碎片。

您的问题的解决方案是覆盖 onBackPressed方法,以检查您是否在设置片段中(您可以使用某个指标来检查当前处于活动状态的片段)如果你在Settings只是重新打开MainFragment

@Override
public void onBackPressed() {
        if (inSettingsFragment)
           showFragment(MainFragment.newInstance(),MainFragment.TAG_MAINFRAGMENT,null,true);
       else { finish();}
    }

答案 1 :(得分:2)

以您希望的方式覆盖onBackPressed() MainActivity中的Settings,您可以检查自己是否在Main片段中,如果是,则不退出,只是请改为显示Main片段,如果您在finish()片段中,则可以拨打var BaseView = Backbone.View.extend({ getTemplate: function () { return template; } }); var MyView = BaseView.extend({ template: 'dummy', initialize: function () { // Do stuff }, render: function () { // Do render stuff } });