片段OnBackPressed?

时间:2015-11-24 05:30:15

标签: android android-fragments

我怀疑我内部有一个活动,即有三个片段,即a,b,c交易将像a-> b->。我的疑问是当我从b输入后退按钮它必须去片段a和frag b应该返回到其默认状态我该如何实现它?我真的很困惑,因为我是新手,我希望你们在这里帮忙

这是我的片段代码:

  import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;

import java.util.ArrayList;

public class Leads extends Fragment implements View.OnClickListener {

    public Leads(){}

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

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

        ArrayList<NewsItem> listContact = GetlistContact();
        ListView lv = (ListView) rootView.findViewById(R.id.listView);
        lv.setAdapter(new CustomListAdapter(getActivity(), listContact));


        return rootView;

    }

    private ArrayList<NewsItem> GetlistContact(){
        ArrayList<NewsItem> contactlist = new ArrayList<NewsItem>();

        NewsItem contact = new NewsItem();
        for(int i=1;i<=30;i++) {
            contact = new NewsItem();
            contact.setHeadline("Yoge " +i);
            contact.setReporterName("Yogeshwaran" + i);
            contact.setLeadsource("Yogan" + i);
            contact.setLeadStatus("open" + i);
            contact.setLeadType("Business"+i);
            contactlist.add(contact);

        }

        return contactlist;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Fragment fragment=null;
        Button add = (Button) getActivity().findViewById(R.id.btnadd);
        add.setOnClickListener(this);
        ImageButton   filter = (ImageButton) getActivity().findViewById(R.id.btnfilter);
        filter.setOnClickListener(this);

    }
    String str="";
    @Override

    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnadd:
                Fragment newFragment = new Add();
                str="add";
                // consider using Java coding conventions (upper first char class names!!!)
                FragmentTransaction transaction = getFragmentManager().beginTransaction();

                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack
                transaction.replace(R.id.content_frame, newFragment,str);
                transaction.addToBackStack(null);

                // Commit the transaction
                transaction.commit();

        }
    }



}

这是我的frag b代码:

    package first.service.precision.servicefirst;

/**
 * Created by 4264 on 23-11-2015.
 */
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by 4264 on 16-10-2015.
 */
public  class Add extends Fragment implements View.OnClickListener {
    public static ListView lv;
    static String sbu, sbuu, sc, ssc, req;
    static String bu;
    customListAdapterldrequirements customListAdapterldrequirements;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        try {
            View rootView = inflater.inflate(R.layout.activity_btn_add, container, false);
            Spinner ldsource = (Spinner) rootView.findViewById(R.id.lead_source);
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                    getActivity().getBaseContext(), R.array.dropbox1, R.layout.spinnerlayout);


            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            ldsource.setAdapter(adapter);
            //   EditText editText=(EditText)rootView.findViewById(R.id.title);

            Spinner ldtype = (Spinner) rootView.findViewById(R.id.ldtype);
            ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
                    getActivity().getBaseContext(), R.array.dropbox2, R.layout.spinnerlayout);

            adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            ldtype.setAdapter(adapter1);
            Spinner ldstatus = (Spinner) rootView.findViewById(R.id.ldstatus);
            TextView txt = (TextView) rootView.findViewById(R.id.spinnerTarget);
            ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
                    getActivity().getBaseContext(), R.array.dropbox3, R.layout.spinnerlayout);

            adapter2.setDropDownViewResource(android.R.layout.simple_selectable_list_item);
            ldstatus.setAdapter(adapter2);
            //  Bundle bundle=getArguments();
            //  String good=bundle.getString("sbu");


            Bundle bundle = getArguments();

//            sbu = getArguments().getString("yes");
            ArrayList<LdNewsItem> listContact = GetlistContact();

            //    public boolean onTouch(View v, MotionEvent event) {
            //        return false;
            // }

            // Setting on Touch Listener for handling the touch inside ScrollView


            //});
            lv = (ListView) rootView.findViewById(R.id.ldrequirements);
            customListAdapterldrequirements = new customListAdapterldrequirements(getActivity(), listContact);
            lv.setAdapter(customListAdapterldrequirements);
            // customListAdapterldrequirements customListAdapterldrequirements=new customListAdapterldrequirements(getActivity(),listContact);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                                        long id) {
                    NewRequirements newRequirements = new NewRequirements();
                    FragmentManager fm = getFragmentManager();
                    FragmentTransaction ft = fm.beginTransaction();
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

                    //  lv.deferNotifyDataSetChanged();
                    ft.replace(R.id.content_frame, newRequirements, "hi");
                    ft.addToBackStack(null);
                    ft.commit();

                }
            });
      /*  lv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }


            // Setting on Touch Listener for handling the touch inside ScrollView
      //      @Override
        //    public boolean onTouch(View v, MotionEvent event) {
                // Disallow the touch request for parent scroll on touch of child view

          //      v.getParent().requestDisallowInterceptTouchEvent(true);
//
  //              return false;
    //        }
        });*/
            return rootView;

        } catch (Exception e) {
            throw e;
        }
    }

    public void updateListView() {
        customListAdapterldrequirements.notifyDataSetChanged();
    }

    private ArrayList<LdNewsItem> GetlistContact() {
        ArrayList<LdNewsItem> contactlist = new ArrayList<LdNewsItem>();
        //    String str=getArguments().getString("yes");

        sbu = Main2Activity.sbu;
        bu = Main2Activity.bu;
        sbuu = Main2Activity.sbuu;
        sc = Main2Activity.sc;
        ssc = Main2Activity.ssc;
        req = Main2Activity.req;
        for (int i = 1; i <= 5; i++) {
            LdNewsItem contact = new LdNewsItem();
            contact.setSbu(sbu);
            contact.setBu(bu);
            contact.setSbuu(sbuu);
            contact.setSc(sc);
            contact.setSsc(ssc);
            contact.setReq(req);
            // contact.setReporterName("No matter how big your house is, how recent your car is, or how big your bank account is — our graves will always be the same size. Stay humble." + i);
            contactlist.add(contact);
//lv.setAdapter((ListAdapter) contactlist);

        }

        return contactlist;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Fragment fragment = null;
        setHasOptionsMenu(true);
        Button btnrequirements = (Button) getActivity().findViewById(R.id.btnrequirements);
        btnrequirements.setOnClickListener(this);
        Button btnactnt = (Button) getActivity().findViewById(R.id.btnacnt);
        btnactnt.setOnClickListener(this);
        Button btnprimary = (Button) getActivity().findViewById(R.id.btnprimary);
        btnprimary.setOnClickListener(this);
        Button btnsecondary = (Button) getActivity().findViewById(R.id.btnsecondary);
        btnsecondary.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnrequirements:
                Fragment newFragment = new NewRequirements();
                // consider using Java coding conventions (upper first char class names!!!)
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack
                transaction.replace(R.id.content_frame, newFragment);
                transaction.addToBackStack(null);
                // Commit the transaction
                transaction.commit();
                break;

            case R.id.btnacnt:
                FragmentManager fm = getFragmentManager();
                //FragmentTransaction ft=fm.beginTransaction();
                SelectAccountDialog selectAccountDialog = new SelectAccountDialog();
                selectAccountDialog.setRetainInstance(true);
                selectAccountDialog.show(fm, "fragment_name");
                //ft.addToBackStack(null);

                break;
            case R.id.btnprimary:
                FragmentManager fmm = getFragmentManager();
                // FragmentTransaction ftt=fmm.beginTransaction();
                SelectAccountDialog selectAccountDialog1 = new SelectAccountDialog();
                selectAccountDialog1.setRetainInstance(true);
                selectAccountDialog1.show(fmm, "fragment_name");
                //   ftt.addToBackStack(null);
                break;
            case R.id.btnsecondary:
                FragmentManager fm2 = getFragmentManager();
                //     FragmentTransaction fttt=fm2.beginTransaction();
                SelectAccountDialog selectAccountDialog2 = new SelectAccountDialog();
                selectAccountDialog2.setRetainInstance(true);
                selectAccountDialog2.show(fm2, "fragment_name");
                //     fttt.addToBackStack(null);
                break;

        }

    }


    /*@Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
        Leads leads=new Leads();
FragmentManager back=getFragmentManager();
        FragmentTransaction ft=back.beginTransaction();
        ft.replace(R.id.content_frame,leads);
        ft.addToBackStack(null);
        ft.commit();


    }*/
}

我的活动如下:

package first.service.precision.servicefirst;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;


public class Main2Activity extends Activity  {

    public static String sbu,bu,sbuu,sc,ssc,req;

    // Within which the entire activity is enclosed
    private DrawerLayout mDrawerLayout;

    // ListView represents Navigation Drawer
    private ListView mDrawerList;
    Button butonlead;
    // ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
    private ActionBarDrawerToggle mDrawerToggle;

    // Title of the action bar
    private String mTitle = "";


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        final ActionBar ab = getActionBar();
        ab.show();
        // Getting reference to the DrawerLayout
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ab.setTitle(mTitle);

        mDrawerList = (ListView) findViewById(R.id.drawer_list);

        // Getting reference to the ActionBarDrawerToggle
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,

                R.string.open_drawer,
                R.string.close_drawer) {

            /** Called when drawer is closed */
            public void onDrawerClosed(View view) {

                invalidateOptionsMenu();

            }

            /** Called when a drawer is opened */
            public void onDrawerOpened(View drawerView) {

                invalidateOptionsMenu();
            }


        };

        // Setting DrawerToggle on DrawerLayout
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        // Creating an ArrayAdapter to add items to the listview mDrawerList
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplication(),
                R.layout.drawer_list_item, R.id.title, getResources().getStringArray(R.array.option));

        // Setting the adapter on mDrawerList
        mDrawerList.setAdapter(adapter);

        // Enabling Home button
        ab.setHomeButtonEnabled(true);
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#53A93F")));
        // Enabling Up navigation
        ab.show();
        ab.setDisplayHomeAsUpEnabled(true);

        // Setting item click listener for the listview mDrawerList
        mDrawerList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // Getting an array of options
                String[] menuItems = getResources().getStringArray(R.array.option);

                // Currently selected option
                mTitle = menuItems[position];

                Fragment fragment = null;
                String tag="";
                switch (position) {
                    case 0:
                        fragment = new Leads();
                        tag="leads";
                        break;
                    case 1:
                        fragment = new Opportunities();
                        break;
                    case 2:
                        fragment = new Accounts();
                        break;
                    case 3:
                        fragment = new Contactss();
                        break;
                    case 4:
                        fragment = new Documents();
                        break;
                    case 5:
                        fragment = new Reports();
                    default:
                        break;
                }
                if (fragment != null) {
                    // Getting reference to the FragmentManager
                    FragmentManager fragmentManager = getFragmentManager();
                    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment,tag).addToBackStack("fragback").commit();
                    // Creating a fragment transaction
                    FragmentTransaction ft = fragmentManager.beginTransaction();

                    // Adding a fragment to the fragment transaction
                    ft.replace(R.id.content_frame, fragment);

                    // Committing the transaction
                    ft.commit();

                    // Closing the drawer
                    mDrawerLayout.closeDrawer(mDrawerList);
                } else {
                    // error in creating fragment
                    Log.e("MainActivity", "Error in creating fragment");
                }

            }
        });
    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            FragmentManager manager = getFragmentManager();

            manager.popBackStack();
            super.onBackPressed();
        }

    }
    public void changeFragment(Fragment fragment, String tag, boolean shouldAddToBackStack) {

        try {
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            if (shouldAddToBackStack)
                ft.addToBackStack(tag);
            else {
                getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }
            ft.replace(R.id.content_frame, fragment, tag)
                    .commit();
            getFragmentManager().executePendingTransactions();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Called whenever we call invalidateOptionsMenu()
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);


        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main2, menu);
        return super.onCreateOptionsMenu(menu);
    }



   /* @Override
    public void DataTransfer(String e) {


    }*/
//
    // @Override
    //  public void DataTransfer(ArrayList<String> e) {
    //     Add obj=(Add)getFragmentManager().findFragmentById(R.id.frag_1);
    //   obj.GetlistContact(e);
    // }
}
  /*  @Override
    public void selectedvalue(String s) {
            Add add=new Add();
            FragmentManager fm=getFragmentManager();
            FragmentTransaction ft=fm.beginTransaction();
            ft.replace(R.id.content_frame,add);
            ft.commit();}
    }
*/

4 个答案:

答案 0 :(得分:0)

你的应用程序只有一个backstack。它是一个堆栈,如果我们将我们的片段添加到这个堆栈,按下后退按钮它会弹出。在您的情况下,您可以添加以下代码来切换片段。在主要活动和父片段中输入此代码。将shouldAddToBackStack传递为true,您要在backstack中添加哪些片段,一旦按下后退按钮,它将自动弹出

你应该替换所有这些

Fragment newFragment = new NewRequirements();
                // consider using Java coding conventions (upper first char class names!!!)
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack
                transaction.replace(R.id.content_frame, newFragment);
                transaction.addToBackStack(null);
                // Commit the transaction
                transaction.commit();

使用此功能

   public void changeFragment(Fragment fragment, String tag, boolean shouldAddToBackStack) {

            try {
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                if (shouldAddToBackStack)
                    ft.addToBackStack(tag);
                else {
                    getActivity().getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                }
                ft.replace(R.id.container, fragment, tag)
                        .commit();
                getActivity().getSupportFragmentManager().executePendingTransactions();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
       }

答案 1 :(得分:0)

当您将第二个片段添加到活动时,将第一个片段添加到后台堆栈:

fragmentTransaction.addToBackStack("fragmentATag");

还会覆盖活动的onBackPressed()方法:

@Override
public void onBackPressed() {
     FragmentManager manager = getSupportFragmentManager();
     if (manager.getBackStackEntryCount() > 0) 
         manager.popBackStack();

}

答案 2 :(得分:0)

编写getActivity()。getFragmentManager()。popBackStack();在onBackPressedMethod()

答案 3 :(得分:0)

你可以这样做:

通过以下代码

替换 片段

android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction ft = fragmentManager.beginTransaction();    
ft.replace(R.id.content_view, new FragmentB());
ft.addToBackStack(null);
ft.commit();   

无需片段B 中执行代码以返回片段A ,它将自动处理,当您按硬背键时,如果您想片段B 添加自定义按钮 片段A ,而不是必须添加 getActivity.onBackPressed()

希望这会对你有所帮助。