片段无法正常工作

时间:2016-01-08 05:44:30

标签: java android android-fragments navigation-drawer android-tabhost

我在我的应用程序中使用导航抽屉,一切正常,问题是onbackpress我的应用程序越来越近,没有应用程序崩溃,只是我的应用程序正在关闭

以下是我的代码和屏幕截图,有人可以帮忙吗?

MainActivity

@Override
    public void onDrawerItemSelected(View view, int position) {
        displayView(position);
    }

    private void displayView(int position) {
        Fragment fragment = null;
        String title = getString(R.string.app_name);

        switch (position) {
            case 0:
                fragment = new HomeFragment();

                title = getString(R.string.title_home);
                break;
            case 1:
                fragment = new FriendsFragment();


                title = getString(R.string.title_friends);
                break;
            case 2:
                fragment = new MessagesFragment();


                title = getString(R.string.title_messages);
                break;

            case 3:
                fragment = new Profiles();


                title = getString(R.string.title_pro);
                break;
            case 4:
                fragment = new AboutUsFragment();
                title = getString(R.string.title_aboutus);
                break;
            case 5:
                fragment = new FAQ();
                title = getString(R.string.title_faq);
                break;
            case 6:
                fragment = new Privacypolicy();
                title = getString(R.string.title_privacypolicy);
                break;
            case 7:
                fragment = new ContactUs();
                title = getString(R.string.title_contacts);
                break;

            case 8:
                // session.logoutUser();
                LoginManager.getInstance().logOut();
               // Intent intent=new Intent(MainActivity.this,LoginPage.class);
                // startActivity(intent);
                title = getString(R.string.title_logout);
                break;
            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container_body, fragment);
            fragmentTransaction.commit();
            getSupportActionBar().setTitle(title);
        }
    }

   /* @Override
    public void onBackPressed() {

        int count = getFragmentManager().getBackStackEntryCount();

        if (count == 0) {
            super.onBackPressed();
            //additional code
        } else {
            getFragmentManager().popBackStack();
        }

    }*/

    @Override
    public void onBackPressed(){
        FragmentManager fm = getSupportFragmentManager();
        if (fm.getBackStackEntryCount() > 1) {
            Log.i("MainActivity", "popping backstack");
            fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

        } else {
            Log.i("MainActivity", "nothing on backstack, calling super");
            super.onBackPressed();
        }
    }
}

HomeFragment.java

public class HomeFragment extends Fragment {

    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;

    private FragmentTabHost tabHost;
    private SearchView searchView;
    // private String strtext;
    // private String FBIDs;
    // private String GIDs;


    public HomeFragment() {
    }

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

        tabHost = new FragmentTabHost(getActivity());
        tabHost.setup(getActivity(), getChildFragmentManager(), R.layout.my_parent_fragment);
        // strtext = getArguments().getString("user_login_id");


        //  System.out.println("<<<<<<<<<<<<<< Session ID :  " + strtext);

        Bundle arg1 = new Bundle();
        arg1.putInt("Arg for Frag1", 1);
       /* if(strtext!=null) {
            arg1.putString("user_logid", strtext);
        }*/

        tabHost.addTab(tabHost.newTabSpec("one").setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_profile_tabs, "Home")), DiscoverFragment.class, arg1);
        Bundle arg2 = new Bundle();

        arg2.putInt("Arg for Frag2", 2);

       /* if(strtext!=null) {
            arg2.putString("user_logid_sectab", strtext);
        }*/

        tabHost.addTab(tabHost.newTabSpec("Sec").
                setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_frnds_tab, "Invite")), ShopFragment.class, arg2);


        Bundle arg3 = new Bundle();
        arg3.putInt("Arg for Frag3", 3);

      /*  if(strtext!=null) {
            arg3.putString("user_logid_thirdtab", strtext);
        }*/

        tabHost.addTab(tabHost.newTabSpec("Third").
                setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_wish_tab, "Wish")), Thirdtab.class, arg3);


        Bundle arg4 = new Bundle();
        arg4.putInt("Arg for Frag4", 4);
        /*if(strtext!=null) {
            arg4.putString("user_logid_fourthtab", strtext);
        }*/

        tabHost.addTab(tabHost.newTabSpec("Four").
                setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_notification_tab, "Alert")), FourthTabs.class, arg4);

        return tabHost;


    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

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

    public View getTabIndicator(Context context, int icon, String text) {
        View view = LayoutInflater.from(context).inflate(R.layout.tab_layout, null);
        ImageView iv = (ImageView) view.findViewById(R.id.indicatorImageView);
        iv.setImageResource(icon);
        TextView txt = (TextView) view.findViewById(R.id.txttb);
        txt.setText(text);
        return view;
    }


}

DiscoverFragment.java

public class DiscoverFragment extends Fragment {


    private Button btn;

    public DiscoverFragment() {
    }

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

        View rootView = inflater.inflate(R.layout.discover_frag, container, false);

        btn=(Button)rootView.findViewById(R.id.btnhomf);

        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                WishaFriend ff = new WishaFriend();

                android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
                android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
                fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
               // ft.replace(R.id.container_body,ff);
               ft.replace(((ViewGroup) getView().getParent()).getId(), ff);

                // fm.addToBackStack("sds");
               ft.commit();
            }
        });

        return rootView;
    }

}

当我运行应用程序时,它将此显示为第一个屏幕

enter image description here

然后我点击gotonextfrag按钮,它将重定向到下一个frag,我将收到此屏幕

enter image description here

现在从这个片段,如果我按设备的后退按钮我的应用程序关闭

XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">



        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            style="@style/MyToolBarStyle.Base"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"

            >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"

                android:src="@drawable/toolbartitle"/>

        </android.support.v7.widget.Toolbar>


    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawerLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <!-- activity view -->
        <!-- Framelayout to display Fragments -->
        <FrameLayout
            android:id="@+id/container_body"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <!-- navigation drawer -->
        <fragment
            android:id="@+id/fragment_navigation_drawer"
            android:name="com.balloons.balloonationn.activity.FragmentDrawer"
            android:layout_width="@dimen/nav_drawer_width"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:layout="@layout/fragment_navigation_drawer"
            tools:layout="@layout/fragment_navigation_drawer" />

    </android.support.v4.widget.DrawerLayout>

</LinearLayout>

5 个答案:

答案 0 :(得分:1)

这是Activity的正常行为。当您按后退按钮时,它将完成当前活动。

Override back button

答案 1 :(得分:0)

我认为你没有加入BackStack

想要显示fragment

时尝试此操作
public void showFragment(Fragment fragment, String title) {
    if (fragment != null) {
        String backStateName = fragment.getClass().getName();
        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.replace(R.id.dashboard_container, fragment);
        mFragmentTransaction.addToBackStack(backStateName);
        mFragmentTransaction.commit();
        setActionBarTitle(title);
        if (backStateName == DashBoardFragment.class.getSimpleName()) {
            clearBackStack();
        }
    }
}

并在onBackPressed()

@Override
public void onBackPressed() {
    if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
        mDrawerLayout.closeDrawers();
    } else {
        int backStackCount = mFragmentManager.getBackStackEntryCount();
        if (backStackCount > 0) {
            popFragments(backStackCount);
        } else {
            finish();
        }
    }
}

private void popFragments(int backStackCount) {
    String fragmentTag = mFragmentManager.getBackStackEntryAt(
            backStackCount - 1).getName();
    if (!TextUtils.isEmpty(fragmentTag)) {
        Fragment currentFragment = mFragmentManager
                .findFragmentById(R.id.dashboard_container);
        if (currentFragment != null && currentFragment instanceof HomeFragment) {
            finish();
        } else {
            mFragmentManager.popBackStack();
        }
    }
}

private void clearBackStack() {
    mFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    setSelectedItem(Numerics.ZERO);
}

答案 2 :(得分:0)

将此添加到您的fragmentTransaction。

$(document).ready(function() {

$('#date_start').change(function(){

var startdate = $('#date_start').datepicker("getDate");
var today = new Date();  
var tomorrow = today.add(2).day();
if(startdate.getTime() < today.getTime()){
    document.getElementById('finish').disabled = true;
}
else{

答案 3 :(得分:0)

在您的代码中尝试此操作

  FragmentManager fragmentManager = getSupportFragmentManager();
  FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
  fragmentTransaction.replace(R.id.container_body, fragment);
  fragmentTransaction.addToBackStack("messages"); /** Add this line**/
  fragmentTransaction.commit();

这将在你的后台堆叠中添加片段,这在你的情况下不会发生。

在你的onBackPressed

 @Override
    public void onBackPressed() {
        // if drawer is open
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {

            if(fragmentManager.getBackStackEntryCount() == 0)
                Log.d(TAG,"fragment count = 0 "); /** here your fragment count is 0. Add alert to exit app **/
            else
               super.onBackPressed();
        }
    }

答案 4 :(得分:0)

  1. 按以下方式添加片段 -

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.myFrame, new FirstFrag(), null)
            .addToBackStack(null)
            .commit();
    
  2. 更改你的onBackPressed()mth,如下所示

    @Override
    public void onBackPressed(){
        FragmentManager fm = getSupportFragmentManager();
    
        if (fm.getBackStackEntryCount() > 1) {
            fm.popBackStack();
    
        } else {
            super.onBackPressed();
        }
    }