How to remove fragment when I rotate my tablet

流过昼夜 提交于 2019-12-08 12:35:51

问题


I have 2 fragments which are called from the action bar of an activity. Both are gridviews, the first one displays an application list with a dedicated adapter, and the second one displays a file list with another adapter. My problem is that when I launch a file then when I back to my activity I switch from one fragment to another, when I come back to the previous one, its content disappears. And when I rotate tablet I have the some problem, because my Fragment restart so for this I think that removing fragment give the possibility to create a new Fragment up to date.

How can I manage to update the content of the first fragment while coming back from the second one ? And how to remove fragment after the rotation in order to recreate the Action with new Fragment? the code of my Activity is given by the code below:

public class LaunchActivity extends Activity {

    public static Activity LAUNCH;

    private PagerAdapter mPagerAdapter;
    Menu menu;
    public static boolean updated = false;

    private static final String TAG = "launchactivity";
    public static String Path2;
    public static String[] mMenu;
    public static String file_name = "seconde";
    public static String teacher_file = "teacher";
    public static String newString;
    public static String SESSIONNAME;
    public static ArrayList<String> myList;
    private static ArrayList<String> test;
    String user = "eleve";
    String savedUser;
    String mode = "normal";
    String savedMode;
    private int year;
    private int month;
    private int day;
    static final int DATE_DIALOG_ID = 999;

    public static boolean active = false;

    ////////////////////
//  OptionsActivity fi = new OptionsActivity();
    private ApplicationManager appManager;
    ArrayList<String> files = new ArrayList<String>();

    private List<String> listTitle = new ArrayList<String>();

    private final BroadcastReceiver mApplicationsReceiver = new ApplicationsIntentReceiver();

    private boolean mHomeDown;
    private boolean mBackDown;
     private ActionBar actionbar ;
    File mntFolder = new File("/mnt/");
    File[] external = mntFolder.listFiles();

    public static boolean pause2=false;
    public static String path;
    public static File fpath;
    private boolean admin = false;
    private boolean eleve = false;
    private boolean prof = false;

    ///////////////////////

    private static final String TAB_KEY_INDEX = "tab_key";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main1);

        LAUNCH = this;
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if(extras == null) {
                newString= null;
            } else {
                newString= extras.getString(PreferenceConnector.PREF_NAME);
            }
        } else {
            newString= (String) savedInstanceState.getSerializable(PreferenceConnector.PREF_NAME);
        }
       // Log.i("**----test----saved value**" , newString);
        if(newString != null){
            newString = newString.substring(1 , (newString.length()-1));

            ArrayList<String> sList  =  new ArrayList<String>(Arrays.asList(newString.split(",")));
            myList = new ArrayList<String>(Arrays.asList(newString.split(", ")));
            String v = " ";
            myList.add(0, v.concat(sList.get(0)));
            myList.add(0, sList.get(0).concat(v));
            /////// try this  in order to get the good size///////////////////////////////
            for(int i= 0 ; i< myList.size() ; i++){
                Log.i("------> l'element n " + String.valueOf(i),myList.get(i));

            }
        }

        if (savedInstanceState != null) {
            savedUser = savedInstanceState.getString("TEXT");
            savedMode = savedInstanceState.getString("MODE");
            String str;
            str = savedInstanceState.getString("ListActivity");
             test = savedInstanceState.getStringArrayList("List");
           // myList = (ArrayList<String>) Arrays.asList(str.split("\\s*,\\s*"));

        } else {
            savedUser = "eleve";
            savedMode = "normal";

        }
        //Log.d("savedUser", savedUser);
        //Log.d("savedMode", savedMode);

        // ActionBar
        actionbar = getActionBar();
        actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionbar.setDisplayUseLogoEnabled(false);
        actionbar.setDisplayShowTitleEnabled(false) ;
        // create new tabs and and set up the titles of the tabs
        ActionBar.Tab mFindTab = actionbar.newTab().setText(
                getString(R.string.ui_tabname_find));
        ActionBar.Tab mChatTab = actionbar.newTab().setText(
                getString(R.string.ui_tabname_chat));
        ActionBar.Tab mMeetTab = actionbar.newTab().setText(
                getString(R.string.ui_tabname_meet));
        ActionBar.Tab mPartyTab = actionbar.newTab().setText(
                getString(R.string.ui_tabname_find));

        // create the fragments
        Fragment mMeetFragment = new  ApplicatinFragment();
        Fragment mFindFragment = new MatFragment();
        Fragment mChatFragment = new DocumentFragment1();

        Fragment mPartyFragment = new PartyFragment();

        // bind the fragments to the tabs - set up tabListeners for each tab
        mFindTab.setTabListener(new MyTabsListener(mFindFragment,
                getApplicationContext()));
        mChatTab.setTabListener(new MyTabsListener(mChatFragment,
                getApplicationContext()));
        mMeetTab.setTabListener(new MyTabsListener(mMeetFragment,
                getApplicationContext()));
//      mPartyTab.setTabListener(new MyTabsListener(mPartyFragment,
//              getApplicationContext()));

        // add the tabs to the action bar
        actionbar.addTab(mMeetTab);
        actionbar.addTab(mFindTab);


        if (savedInstanceState != null) {
         //   Toast.makeText(getApplicationContext(),
           //         "tab is " + savedInstanceState.getInt(TAB_KEY_INDEX, 0),
             //       Toast.LENGTH_SHORT).show();

            actionbar.setSelectedNavigationItem(savedInstanceState.getInt(
                    TAB_KEY_INDEX, 0));
        }

    }
    public void onResume() {

        this.stopService(new Intent(this, fr.mi.DetectorService.class));
        Intent startService = new Intent(this, fr.mi.DetectorService.class);
        this.startService(startService);

        if(fr.mi.LockScreenActivity.LOCK != null){
            fr.mi.LockScreenActivity.LOCK.finish();
        }
        Log.i("onResume", "onResume()");
        if (AppList.ac != null) {
            AppList.ac.finish();
        }
        //Toast.makeText(this, "onResume()", Toast.LENGTH_LONG).show();
        super.onResume();

    }

    @Override
public void onPause() {
    super.onPause();  // Always call the superclass method first

}
    public void onDestroy() {
        super.onStop();
        //  tToast("onDestroy.");
    }

    private class ApplicationsIntentReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(getApplicationContext(), "test" +  "this" , Toast.LENGTH_LONG).show();
            appManager.loadApplications(false);

        }
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        /*
        Toast.makeText(
                this,
                "onSaveInstanceState: tab is"
                        + getActionBar().getSelectedNavigationIndex(),
                Toast.LENGTH_SHORT).show();   */
        outState.putStringArrayList("List",LaunchActivity.myList);
        outState.putString("ListActivity", LaunchActivity.myList.toString());

    }

    private void registerIntentReceivers() {
        IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
        filter.addDataScheme("package");
        registerReceiver(mApplicationsReceiver, filter);
    }


}



class MyTabsListener implements ActionBar.TabListener {
    public Fragment fragment;
    public Context context;

    public MyTabsListener(Fragment fragment, Context context) {
        this.fragment = fragment;
        this.context = context;

    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
       // Toast.makeText(context, "Reselected!", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        //Toast.makeText(context, "Selected!", Toast.LENGTH_SHORT).show();
        ft.replace(R.id.fragment_container, fragment);
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        //Toast.makeText(context, "Unselected!", Toast.LENGTH_SHORT).show();
        ft.remove(fragment);
    }    
}

My first Fragment used to view installed application in a gridView. is given by the code below:

public class ApplicatinFragment extends Fragment {
    TextView title;
    private static ApplicationManager appManager;

    Menu menu;
    public static boolean updated = false;

    private static final String TAG = "launchactivity";
    public static String Path;
    public static String[] mMenu;
    public static String file_name = "seconde";
    public static String teacher_file = "teacher";
    //private static final String PREF_APPLICATION_LIST = "application_list";
    //OptionsActivity fi = new OptionsActivity();

    private static final String PREF_SERVICE_ENABLED = "service_enabled";
    private static final String PREF_APPLICATION_LIST = "application_list";
    private static final String PREF_APPLICATION_LIST1 = "application_list1";
    private static final String PREF_APPLICATION_LISTPROF = "application_list_prof";
    private static final String PREF_AUTO_START = "start_service_after_boot";
    private static final String PREF_PASSWORD = "password";
    private static final String PREF_UNIVERSEL_PASSWORD = "universelpassword";
    public static boolean SBACKSTUCK = false ;

    private SharedPreferences mPref;

    private boolean mServiceEnabled, mAutoStart;
    public static String[] mApplicationList;
    private String[] mApplicationList1;
    private String[] mApplicationListProf;
    public static String mPassword;
    private String mUniverselPassword;
    private int mRelockTimeout;
    private final BroadcastReceiver mApplicationsReceiver = new ApplicationsIntentReceiver();
      GridView gridView;


    ArrayList<String> files = new ArrayList<String>();

    private static GridViewAppInfoAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("PageAdminFragment", "onCreate");
        appManager = new ApplicationManager(getActivity(), getActivity()
                .getPackageManager(),LaunchActivity.myList);
        appManager.loadApplications(true);

        registerIntentReceivers();
        adapter = new GridViewAppInfoAdapter(getActivity(),
                appManager.getStudentApplicationsCode());

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        SharedPreferences.Editor editor = sharedPreferences.edit();
//        mApplicationList = mPref.getString(PREF_APPLICATION_LIST, "").split(";");

        String combined = "";

        combined =  combined + "com.android.vending"  + ";";
        combined =  combined + "com.android.settings" + ";";
        combined = combined + "com.android.packageinstaller" + ";" ;
        //combined = combined + "air.Arbres";

        for( int i = 0; i < SessionChoose.ProtectedApplication.size(); i++){
            combined = combined + SessionChoose.ProtectedApplication.toString() + ";" ;
        }

        Log.d("-*-*les applications à proteger-*-*", combined);
        //Toast.makeText(getActivity(),"-*-*les applications à proteger-*-*"+ combined,Toast.LENGTH_LONG).show();
       // editor.putString(PREF_APPLICATION_LIST, combined).commit();

        // LoadPreferences(getActivity());
        //Toast.makeText(getApplicationContext(),"PREF_APPLICATION_LIST " + strSavedMem2 , Toast.LENGTH_LONG ).show();
        // SaveApplicationPreferences(PREF_APPLICATION_LIST,strSavedMem2 ,ProtectedApplication,getApplicationContext());

        //LoadPreferences(getActivity());
        //Toast.makeText(getApplicationContext(),"PREF_APPLICATION_LIST " + strSavedMem2 , Toast.LENGTH_LONG ).show();
        //LoadPreferences(getActivity());
        /**
         * Creat file to save session Content
         */
        this.getActivity().getApplicationContext().stopService(new Intent(this.getActivity(), fr.mi.DetectorService.class));
        //getActivity().stopService(new Intent(this.getActivity(), fr.mi.DetectorService.class));


    }

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




        //Toast.makeText(getActivity(), "I need the good Adapter", Toast.LENGTH_SHORT).show();
        Log.d(TAG, appManager.getStudentApplications().toString());

        int display_mode = getResources().getConfiguration().orientation;


          View view = null;


        /////////////////////////////////////////////////////////////////////////////
        if (display_mode == 1) {
             view = inflater.inflate(R.layout.main_grid,
                    container, false);
            // this.getWindow().setFlags(
            // WindowManager.LayoutParams.FLAG_FULLSCREEN,
            // WindowManager.LayoutParams.FLAG_FULLSCREEN);
            // this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            gridView = (GridView) view.findViewById(R.id.gridview);
            //mGrid = (GridView) findViewById(R.id.gridview);
            gridView.setColumnWidth(95);

            // mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

        } else {
            view = inflater.inflate(R.layout.main_grid_land,
                    container, false);
            // this.getWindow().setFlags(
            // WindowManager.LayoutParams.FLAG_FULLSCREEN,
            // WindowManager.LayoutParams.FLAG_FULLSCREEN);
            //setContentView(R.layout.main_grid_land);
            gridView = (GridView) view.findViewById(R.id.gridview1);

            gridView.setColumnWidth(95);

            Log.d("Mode", "land");
            // mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

        }
        gridView.setAdapter(adapter);
        gridView.setSelection(0);
        /////////////try this ///////////////////////
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.getActivity().getApplicationContext());
        SharedPreferences.Editor editor = sharedPreferences.edit();
        gridView.setOnItemClickListener((new OnItemClickListener() {
            // si on clique sur l'item
            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                                    int position, long id) {

                ApplicationInfo app = (ApplicationInfo) parent
                        .getItemAtPosition(position);
                startActivity(app.intent);
            }
        }));
        if(ViewPagerActivity.VIEWDOC == true  ){

            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);

            intent.setClass(getActivity(), LaunchActivity.class);
            startActivity(intent);

        }

        Intent startService = new Intent(this.getActivity().getApplicationContext(), fr.mi.DetectorService.class);
        getActivity().startService(startService);

        ViewPagerActivity.VIEWDOC = false ;
        return view;

    }

    private void bindApplications(LayoutInflater inflater, ViewGroup container) {

        View view = inflater.inflate(R.layout.main_grid,
                container, false);
        if (gridView == null) {

            gridView = (GridView) view.findViewById(R.id.gridview);
        }


        adapter = new GridViewAppInfoAdapter(getActivity(),
                appManager.getStudentApplicationsCode());
        adapter.notifyDataSetChanged();
        gridView.setAdapter(adapter);
        gridView.setSelection(0);

    }


    private void registerIntentReceivers() {
        IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
        filter.addDataScheme("package");
        getActivity().registerReceiver(mApplicationsReceiver, filter);
    }


    @Override
    public void onStop() {
        super.onStop();
        Log.i(TAG, "Onstop");
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "OnsdESTROY");
        super.onDestroy();
    }

    @Override
    public void onResume() {
        Log.i(TAG, "OnResume");
        super.onResume();
    }

    private void reloadPreferences() {
        mServiceEnabled = mPref.getBoolean(PREF_SERVICE_ENABLED, false);
        mApplicationList = mPref.getString(PREF_APPLICATION_LIST, "").split(";");
        mApplicationList1 = mPref.getString(PREF_APPLICATION_LIST1, "").split(";");
        mApplicationListProf = mPref.getString(PREF_APPLICATION_LISTPROF,"").split(";");
        //Log.d("**************La Liste des applications à proteger***********", mApplicationList.toString());
        Log.i("+-+-+-+-+- ***Censored***++++++++++", mApplicationList.toString() );
        mAutoStart = mPref.getBoolean(PREF_AUTO_START, false);
        mPassword = mPref.getString(PREF_PASSWORD, "2492");
        mUniverselPassword = mPref.getString(PREF_UNIVERSEL_PASSWORD , "9113");

        if (mPref.getBoolean("relock_policy", true)){
            try{
                mRelockTimeout = Integer.parseInt(mPref.getString("relock_timeout", "-1"));
            }catch(Exception e){
                mRelockTimeout = -1;
            }
        }else{
            mRelockTimeout = -1;
        }
    }


    /**
     * Receives notifications when applications are added/removed.
     */
    private class ApplicationsIntentReceiver extends BroadcastReceiver {
        LayoutInflater inflater;
        ViewGroup container  ;

        public ApplicationsIntentReceiver(){

        }
      /* public ApplicationsIntentReceiver(LayoutInflater inflater, ViewGroup container){
          this.inflater = inflater ;
          this.container = container ;
        }*/
        @Override
        public void onReceive(Context context, Intent intent) {

               // appManager = new ApplicationManager(getActivity(), getActivity()
                //.getPackageManager(), null);
            SBACKSTUCK = true;
             appManager.loadApplications(false);
           // gridView.setAdapter(null);
            //GridViewAppInfoAdapter adapter1 = new GridViewAppInfoAdapter(getActivity(),
              //      appManager.getStudentApplicationsCode());
            //adapter1.setApps((List<ApplicationInfo>) appManager.getStudentApplicationsCode());
            //gridView.setAdapter(adapter1);
      //    Toast.makeText(getActivity(), "la valeur" + LaunchActivity.myList.toString() , Toast.LENGTH_LONG).show();
            Log.d("la valeur de la list" ,LaunchActivity.myList.toString() );

        //adapter = new GridViewAppInfoAdapter(getActivity(),
          //      appManager.getStudentApplicationsCode());


            bindApplications( inflater , container);
        }
    }


    ////implement the bind Application

    private void bindApplications(AdapterView<?> parent, int position){

        ApplicationInfo app = (ApplicationInfo) parent
                        .getItemAtPosition(position);
                startActivity(app.intent);
    }

    // ///////////////////////////////////////////////
    /**
     * Starts the selected activity/application in the grid view.
     */
    private class ApplicationLauncher implements
            AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView parent, View v, int position,
                                long id) {
            ApplicationInfo app = (ApplicationInfo) parent
                    .getItemAtPosition(position);
            startActivity(app.intent);
        }

    }

    // //////////////////////////////////////////////
    public boolean onKeyDown(int k, KeyEvent ev) {
        return false;
    }


    public void onBackPressed() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        // finish();
    }


}

The second fragment is used to view a gridview of file is given by the code below:

public class MatFragment extends Fragment {
    private GridViewAjoutFile adapter;
    private GridViewAjoutFile ajout = new GridViewAjoutFile();
    public static boolean continuer = false;
    public static GridviewAdapter mAdapter ;
    public static ArrayList<String> listCountry = new ArrayList<String>();
    public static ArrayList<Integer> listFlag = new ArrayList<Integer>();
    private ArrayList<String> intentType;
    private GridView gridView;
    private String mStackLevel = " ";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final ArrayList<String> profilTabShortCut;
        View view = inflater.inflate(R.layout.maindoc,
                container, false);

        if (savedInstanceState != null) {

            mStackLevel = savedInstanceState.getString("level");
        }
        prepareList();
        mAdapter = new GridviewAdapter(getActivity(),listCountry, listFlag);
        //mAdapter.setFile(listCountry , listFlag);
        gridView = (GridView) view.findViewById(R.id.gridView2);
         //gridView.setAdapter(null);
        gridView.setAdapter(mAdapter);
        // Implement On Item click listener
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {               SetIntentType(SessionChoose.listofUrl.get(position),intentType.get(position));
            }
        });

        return view;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("level", listCountry.toString());
    }

    @Override
    public void onResume() {
        Log.e("DEBUG", "onResume of LoginFragment");

        listCountry = removeDuplicate(listCountry);
        //listFlag = removeDuplicate1(listFlag);

        super.onResume();
    }

    public static ArrayList<String> removeDuplicate(ArrayList<String> arlList) {
        HashSet h = new HashSet(arlList);
        arlList.clear();
        arlList.addAll(h);
        return arlList;
    }
    public static ArrayList<Integer> removeDuplicate1(ArrayList<Integer> arlList) {
        HashSet h = new HashSet(arlList);
        arlList.clear();
        arlList.addAll(h);
        return arlList;
    }

    public Intent SetIntentType(String url, String intenttype ){
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        return null;
    }

    public void prepareList()
    {        intentType = new ArrayList<String>();
        listCountry.clear();
        listFlag.clear();
        if(SessionChoose.listofDoc.size()>0){
            for(int i = 0; i< SessionChoose.listofDoc.size() ; i++){

                listCountry.add(SessionChoose.listofDoc.get(i));
                 String filenameArray[] = SessionChoose.listofDoc.get(i).split("\\.");
                 String extension = filenameArray[filenameArray.length-1];             
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser)
    {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {

        }
    }

    private class ApplicationsIntentReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
           // appManager.loadApplications(false);
           // Intent inte = new Intent(getActivity(),LauncherGridActivity.class);
           //startActivity(inte);

        }
    }

}

回答1:


You can use -

 @Override 
    public void setUserVisibleHint(boolean isVisibleToUser) 
    {
        super.setUserVisibleHint(isVisibleToUser); 
        if (isVisibleToUser) {

        }
    }


来源:https://stackoverflow.com/questions/21601578/how-to-remove-fragment-when-i-rotate-my-tablet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!