2015-09-17 29 views
0

我試圖禁用手機上的硬件backbutton只是這一個特定的片段。禁用片段中的硬件backbutton

片段:

public class Second_frag extends android.support.v4.app.Fragment { 

    String RSSFEEDURL = "http://feeds.feedburner.com/TwitterRssFeedXML?format=xml"; 
    RSSFeed feed; 
    String fileName; 

    View myView; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 
     myView = inflater.inflate(R.layout.splash,container,false); 
     ((AppCompatActivity) getActivity()).getSupportActionBar().hide(); 


     fileName = "Feed.td"; 

     File feedFile = getActivity().getBaseContext().getFileStreamPath(fileName); 

     ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); 
     if (conMgr.getActiveNetworkInfo() == null) { 

      // No connectivity. Check if feed File exists 
      if (!feedFile.exists()) { 

       // No connectivity & Feed file doesn't exist: Show alert to exit 
       // & check for connectivity 
       AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
       builder.setMessage(
         "Unable to reach server, \nPlease check your connectivity.") 
         .setTitle("TD RSS Reader") 
         .setCancelable(false) 
         .setPositiveButton("Exit", 
           new DialogInterface.OnClickListener() { 
            @Override 
            public void onClick(DialogInterface dialog, 
                 int id) { 
             getActivity().finish(); 
            } 
           }); 

       AlertDialog alert = builder.create(); 
       alert.show(); 
      } else { 

       // No connectivty and file exists: Read feed from the File 
       Toast.makeText(Second_frag.this.getActivity(), "No connectivity. Reading last update", Toast.LENGTH_LONG).show(); 
       feed = ReadFeed(fileName); 
       startLisActivity(feed); 
      } 

     } else { 

      // Connected - Start parsing 
      new AsyncLoadXMLFeed().execute(); 

     } 
     return myView; 


    } 

    private void startLisActivity(RSSFeed feed) { 

     Bundle bundle = new Bundle(); 
     bundle.putSerializable("feed", feed); 
     List_Activity fragment = new List_Activity(); 
     fragment.setArguments(bundle); 
     FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); 
     FragmentTransaction transaction = fragmentManager.beginTransaction(); 
     transaction.replace(R.id.workdarnit, fragment).commit(); 


    } 

    private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> { 

     @Override 

     protected Void doInBackground(Void... params) { 

      // Obtain feed 
      DOMParser myParser = new DOMParser(); 
      feed = myParser.parseXml(RSSFEEDURL); 
      if (feed != null && feed.getItemCount() > 0) 
       WriteFeed(feed); 
      return null; 

     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 

      startLisActivity(feed); 
     } 

    } 

    // Method to write the feed to the File 
    private void WriteFeed(RSSFeed data) { 

     FileOutputStream fOut =null ; 
     ObjectOutputStream osw = null; 

     try { 
      fOut = getActivity().openFileOutput(fileName, Context.MODE_PRIVATE); 
      osw = new ObjectOutputStream(fOut); 
      osw.writeObject(data); 
      osw.flush(); 
     } 

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

     finally { 
      try { 
       if(fOut !=null){ 
        fOut.close(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    // Method to read the feed from the File 
    private RSSFeed ReadFeed(String fName) { 

     FileInputStream fIn = null; 
     ObjectInputStream isr = null; 

     RSSFeed _feed = null; 
     File feedFile = getActivity().getBaseContext().getFileStreamPath(fileName); 
     if (!feedFile.exists()) 
      return null; 

     try { 
      fIn = getActivity().openFileInput(fName); 
      isr = new ObjectInputStream(fIn); 

      _feed = (RSSFeed) isr.readObject(); 
     } 

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

     finally { 
      try { 
       if(fIn !=null){ 
        fIn.close(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

     return _feed; 

    } 



    } 

我嘗試添加的片段onbackpress,但它不工作。有誰知道如何解決這個問題?任何幫助,將不勝感激。

編輯:

public class MainActivity extends AppCompatActivity 
     implements NavigationDrawerFragment.NavigationDrawerCallbacks { 

    /** 
    * Fragment managing the behaviors, interactions and presentation of the navigation drawer. 
    */ 
    private NavigationDrawerFragment mNavigationDrawerFragment; 

    /** 
    * Used to store the last screen title. For use in {@link #restoreActionBar()}. 
    */ 
    private CharSequence mTitle; 

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

     mNavigationDrawerFragment = (NavigationDrawerFragment) 
       getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); 
     mTitle = getTitle(); 

     // Set up the drawer. 
     mNavigationDrawerFragment.setUp(
       R.id.navigation_drawer, 
       (DrawerLayout) findViewById(R.id.drawer_layout)); 
    } 

    @Override 
    public void onNavigationDrawerItemSelected(int position) { 


     Fragment myFragment = null; 
     switch (position) { 
      case 0: 
       myFragment = new home(); 
       break; 
      case 1: 
       myFragment = new First_frag(); 
       break; 
      case 2: 
       myFragment = new Second_frag(); 
       break; 
      case 3: 
       myFragment = new Third_frag(); 
       break; 
      case 4: 
       myFragment = new First_frag_o(); 
       break; 
      case 5: 
       myFragment = new QuizF(); 
       break; 
      case 6: 
       myFragment = new Surv_list(); 
       break; 
     } 

     // update the main content by replacing fragments 
     FragmentManager fragmentManager = getSupportFragmentManager(); 
     fragmentManager.beginTransaction() 
       .replace(R.id.container, myFragment) 
       .commit(); 
    } 

    public void onSectionAttached(int number) { 
     switch (number) { 
      case 1: 
       mTitle = getString(R.string.title_section1); 
       break; 
      case 2: 
       mTitle = getString(R.string.title_section2); 
       break; 
      case 3: 
       mTitle = getString(R.string.title_section3); 
       break; 
      case 4: 
       mTitle = getString(R.string.title_section4); 
       break; 
      case 5: 
       mTitle = getString(R.string.title_section5); 
       break; 
      case 6: 
       mTitle = getString(R.string.title_section6); 
       break; 
      case 7: 
       mTitle = getString(R.string.title_section7); 
       break; 
     } 
    } 

    public void restoreActionBar() { 
     ActionBar actionBar = getSupportActionBar(); 
     actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); 
     actionBar.setDisplayShowTitleEnabled(true); 
     actionBar.setTitle(mTitle); 
    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     if (!mNavigationDrawerFragment.isDrawerOpen()) { 
      // Only show items in the action bar relevant to this screen 
      // if the drawer is not showing. Otherwise, let the drawer 
      // decide what to show in the action bar. 
      getMenuInflater().inflate(R.menu.main, menu); 
      restoreActionBar(); 
      return true; 
     } 
     return super.onCreateOptionsMenu(menu); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

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

     return super.onOptionsItemSelected(item); 
    } 

    /** 
    * A placeholder fragment containing a simple view. 
    */ 
    public static class PlaceholderFragment extends Fragment { 
     /** 
     * The fragment argument representing the section number for this 
     * fragment. 
     */ 
     private static final String ARG_SECTION_NUMBER = "section_number"; 

     /** 
     * Returns a new instance of this fragment for the given section 
     * number. 
     */ 
     public static PlaceholderFragment newInstance(int sectionNumber) { 
      PlaceholderFragment fragment = new PlaceholderFragment(); 
      Bundle args = new Bundle(); 
      args.putInt(ARG_SECTION_NUMBER, sectionNumber); 
      fragment.setArguments(args); 
      return fragment; 
     } 

     public PlaceholderFragment() { 
     } 

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

     @Override 
     public void onAttach(Activity activity) { 
      super.onAttach(activity); 
      ((MainActivity) activity).onSectionAttached(
        getArguments().getInt(ARG_SECTION_NUMBER)); 

     } 


    } 



} 
+0

你想要什麼做壓倒性的做,當在片段 –

+0

沒什麼。我需要在打開特定片段時禁用它 – NewGuy117

+0

'onBackPressed()'屬於Activity,而不屬於片段。 –

回答

0

您需要在onBackPressed()方法的活動來處理這個問題。 在該方法中,您查找片段,如果可見,則不執行任何操作。

如果frament不可見,只需調用super.onBackPressed()。

這應該工作。

0

試試這招:

Main Activity 

public class MainActivity extends AppCompatActivity 
     implements NavigationDrawerFragment.NavigationDrawerCallbacks { 

    /** 
    * Fragment managing the behaviors, interactions and presentation of the navigation drawer. 
    */ 
    private NavigationDrawerFragment mNavigationDrawerFragment; 

    /** 
    * Used to store the last screen title. For use in {@link #restoreActionBar()}. 
    */ 
    private CharSequence mTitle; 

Boolean isSecFragmnet=false; 

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

     mNavigationDrawerFragment = (NavigationDrawerFragment) 
       getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); 
     mTitle = getTitle(); 

     // Set up the drawer. 
     mNavigationDrawerFragment.setUp(
       R.id.navigation_drawer, 
       (DrawerLayout) findViewById(R.id.drawer_layout)); 
    } 

    @Override 
    public void onNavigationDrawerItemSelected(int position) { 


     Fragment myFragment = null; 
     switch (position) { 
      case 0: 
       myFragment = new home(); 
isSecFragmnet=false; 
       break; 
      case 1: 
       myFragment = new First_frag(); 
isSecFragmnet=false; 
       break; 
      case 2: 
       myFragment = new Second_frag(); 
isSecFragmnet=true; 
       break; 
      case 3: 
       myFragment = new Third_frag(); 
isSecFragmnet=false; 
       break; 
      case 4: 
       myFragment = new First_frag_o(); 
isSecFragmnet=false; 
       break; 
      case 5: 
       myFragment = new QuizF(); 
isSecFragmnet=false; 
       break; 
      case 6: 
       myFragment = new Surv_list(); 
isSecFragmnet=false; 
       break; 
     } 

     // update the main content by replacing fragments 
     FragmentManager fragmentManager = getSupportFragmentManager(); 
     fragmentManager.beginTransaction() 
       .replace(R.id.container, myFragment) 
       .commit(); 
    } 

    public void onSectionAttached(int number) { 
     switch (number) { 
      case 1: 
       mTitle = getString(R.string.title_section1); 
       break; 
      case 2: 
       mTitle = getString(R.string.title_section2); 
       break; 
      case 3: 
       mTitle = getString(R.string.title_section3); 
       break; 
      case 4: 
       mTitle = getString(R.string.title_section4); 
       break; 
      case 5: 
       mTitle = getString(R.string.title_section5); 
       break; 
      case 6: 
       mTitle = getString(R.string.title_section6); 
       break; 
      case 7: 
       mTitle = getString(R.string.title_section7); 
       break; 
     } 
    } 

    public void restoreActionBar() { 
     ActionBar actionBar = getSupportActionBar(); 
     actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); 
     actionBar.setDisplayShowTitleEnabled(true); 
     actionBar.setTitle(mTitle); 
    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     if (!mNavigationDrawerFragment.isDrawerOpen()) { 
      // Only show items in the action bar relevant to this screen 
      // if the drawer is not showing. Otherwise, let the drawer 
      // decide what to show in the action bar. 
      getMenuInflater().inflate(R.menu.main, menu); 
      restoreActionBar(); 
      return true; 
     } 
     return super.onCreateOptionsMenu(menu); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

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

     return super.onOptionsItemSelected(item); 
    } 

    /** 
    * A placeholder fragment containing a simple view. 
    */ 
    public static class PlaceholderFragment extends Fragment { 
     /** 
     * The fragment argument representing the section number for this 
     * fragment. 
     */ 
     private static final String ARG_SECTION_NUMBER = "section_number"; 

     /** 
     * Returns a new instance of this fragment for the given section 
     * number. 
     */ 
     public static PlaceholderFragment newInstance(int sectionNumber) { 
      PlaceholderFragment fragment = new PlaceholderFragment(); 
      Bundle args = new Bundle(); 
      args.putInt(ARG_SECTION_NUMBER, sectionNumber); 
      fragment.setArguments(args); 
      return fragment; 
     } 

     public PlaceholderFragment() { 
     } 

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

     @Override 
     public void onAttach(Activity activity) { 
      super.onAttach(activity); 
      ((MainActivity) activity).onSectionAttached(
        getArguments().getInt(ARG_SECTION_NUMBER)); 

     } 


    } 

@Override 
      public void onBackPressed() { 


       if (isSecFragment) { 
        //do nothing 
        Log.e("backpressed", "pressed"); 
       } else 

       { 
        super.onBackPressed(); 
       } 
      } 
+0

什麼是片段?是我把Second_frag放在哪裏? – NewGuy117

+0

在你的代碼中你調用ur Second_frag initilaize一個布爾變量true –

+0

顯示我的代碼,其中你調用我的片段我可以幫助你更好 –

0

只是添加到您的活動:

@Override 
public void onBackPressed() { 
    Fragment currFrag = getSupportFragmentManager().findFragmentById(R.id.container); 
    if (currFrag instanceof Second_frag) { 
     //do nothing 
    } else { 
     super.onBackPressed(); 
    } 
} 

,或者如果您更希望片段,以決定是否將使後退按鈕,比所有片段想擴大共同點TemplateFragment

public class TemplateFragment extends android.support.v4.app.Fragment { 
    public boolean enableOnBackPressed() { 
     return true; 
    } 
} 

public class Second_frag extends TemplateFragment { 
    ... 

    @Override 
    public final boolean enableOnBackPressed() { 
     return false; 
    } 
} 

和這個活動:

@Override 
public void onBackPressed() { 
    Fragment currFrag = getSupportFragmentManager().findFragmentById(R.id.container); 
    if (currFrag instanceof TemplateFragment) { 
     if (!((TemplateFragment) currFrag).enableOnBackPressed()) { 
      //do nothing 
      return; 
     } 
    } 
    super.onBackPressed(); 
} 
+0

這是正確的方法,但findFragmentById()可能會返回片段即使不可見(即如果被同一容器或另一容器上的另一片段覆蓋)。可能更好的做findFragmentByTag(),這樣你就不必檢查instanceOf,然後檢查可見性。 – JDenais

+0

第一個工作,但問題是後退按鈕不能在'Second_frag'後啓動的'List_Activity'片段上工作, – NewGuy117