2014-04-29 53 views
0

我有一個應用程序使用片段。它在視圖中有3個片段。最左邊的片段是護理人員名單。中間的片段是另一個名單,這是一個照顧者rota。android刷新選項菜單後加載片段

當加載主屏幕(容納所有3個片段的活動)時,只加載左邊的片段。如果你選擇一個照顧者,中間的片段被裝載(旋轉)。

問題是,用戶可以從optionsMenu中選擇下一個,上一個等,爲給定的護理人員選擇下一個或前一天的rota。如果當前沒有顯示旋轉(中間片段),我不希望optionsMenu顯示下一個或上一個按鈕。

每個rota從AsyncTask加載。在onPostExecute我加載carerdetailsFragment,這是rota。我已經覆蓋了onPrepareOptionsMenu並在那裏檢查是否顯示一個rota。獲得rota後,我還從onPostExecute中調用invalidateOptionsMenu。

optionsMenu首先隱藏按鈕,當只顯示左邊的片段時,但是當你得到一個rota時,它不會更新選項菜單,直到你再次加載rota。

爲什麼invalidateOptionsMenu第一次沒有運行?

<?xml version="1.0" encoding="utf-8"?> 





    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@drawable/carefreebgscaled" 

    > 


    <fragment android:name="com.carefreegroup.rr3.carefreeoncall.CarerListFragment" 
      android:id="@+id/carerlist" 
      android:layout_weight="1" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" /> 


    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/carerdetailsinfofragment_container" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_weight="1" /> 

<!--  <fragment android:name="com.carefreegroup.rr3.carefreeoncall.CarerDetailsFragment" --> 
<!--    android:id="@+id/carerdetails" --> 
<!--    android:layout_weight="1" --> 
<!--    android:layout_width="match_parent" --> 
<!--    android:layout_height="match_parent" /> --> 

<!--  <fragment android:name="com.carefreegroup.rr3.carefreeoncall.CarerPurposeOfCallFragment" --> 
<!--    android:id="@+id/carerpurposeofcall" --> 
<!--    android:layout_weight="1" --> 
<!--    android:layout_width="match_parent" --> 
<!--    android:layout_height="match_parent" /> --> 

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/carerpurposeofcallfragment_container" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_weight="1" /> 

</LinearLayout> 

import org.joda.time.DateTime; 
import org.joda.time.format.DateTimeFormat; 
import org.joda.time.format.DateTimeFormatter; 


import com.carefreegroup.rr3.carefreeoncall.CarerListFragment.OnArticleSelectedListener; 
import com.carefreegroup.rr3.carefreeoncall.RotaDatePicker.OnRotaDatePickerListener; 


import android.app.Activity; 
import android.app.AlertDialog; 
import android.app.Fragment; 
import android.app.FragmentTransaction; 
import android.app.ProgressDialog; 
import android.content.ContentValues; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.pm.ActivityInfo; 
import android.database.Cursor; 
import android.os.AsyncTask; 
import android.os.Bundle; 

import android.util.Log; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.view.View; 

public class OnCallListAndDetailsActivity extends Activity implements OnArticleSelectedListener, OnRotaDatePickerListener{ 

    private static final String TAG = OnCallListAndDetailsActivity.class.getSimpleName(); 
    RROnCallApplication rrOnCallApp; 
    String firstName; 
    String lastName; 
    Intent intent; 
    String carerIDUpdateRota; 
    String updatedRotaDate; 
    DateTime now; 
    String mCarerID; 

    String callStartTime; 
    String callDuration; 
    String callID; 


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



     rrOnCallApp = (RROnCallApplication) getApplication(); 




     setTitle("Carer Update Call"); 

       Cursor carers = rrOnCallApp.dbModel.queryAllFromCarer(); 
       Log.e(TAG, "there are " + carers.getCount() + " in the carer table(OnCallListAndDetailsActivity)"); 


       View CarerDeailsInfoFragContainer = (View)findViewById(R.id.carerdetailsinfofragment_container); 

       if (CarerDeailsInfoFragContainer == null) { 

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 

       } 

       intent = this.getIntent(); 

       Log.e(TAG, "Action of intent = " + intent.getAction()); 


       if (intent.getAction() != null && intent.getAction().equalsIgnoreCase("SHOW_UPDATED_ROTA")){ 

        if (CarerDeailsInfoFragContainer != null) { 

        carerIDUpdateRota = intent.getStringExtra("carerid"); 
        updatedRotaDate = intent.getStringExtra("rotadate"); 

        String[] params = new String[] { carerIDUpdateRota, updatedRotaDate }; 
        AsyncGetRota agr = new AsyncGetRota(); 
        agr.execute(params); 

       }else{ 

        carerIDUpdateRota = intent.getStringExtra("carerid"); 
        updatedRotaDate = intent.getStringExtra("rotadate"); 

        Intent intent = new Intent(this, DisplayCarerDetailsfragmentActivity.class); 
        intent.putExtra("carerid", carerIDUpdateRota); 
        intent.putExtra("date", updatedRotaDate); 

        startActivity(intent); 

       } 
     } 




    }//end of onCreate 




    @Override 
    public void onArticleSelected(String carerId, String _carerFirstName, String _carerLastName, boolean longClick) { 
     // TODO Auto-generated method stub 

     Log.e(TAG, "in onArticleSelected!!"); 

     mCarerID = carerId; 


     CarerPurposeOfCallFragment test = (CarerPurposeOfCallFragment) getFragmentManager().findFragmentById(R.id.carerpurposeofcallfragment_container); 
     if (test != null && test.isVisible()) { 

      Log.e(TAG, "CarerPurposeOfCallFragment is visible"); 


      FragmentTransaction transaction = getFragmentManager().beginTransaction(); 

      // Replace whatever is in the fragment_container view with this fragment, 
      // and add the transaction to the back stack 
      transaction.remove(test); 
      //transaction.addToBackStack(null); 

      // Commit the transaction 
      transaction.commit(); 
     } 
     else { 
      //do nothing 
      Log.e(TAG, "CarerPurposeOfCallFragment is not visible"); 
     } 





      if(longClick == false){ 

       CarerInfoFragment carerInfoFrag = new CarerInfoFragment(); 
       if (carerInfoFrag != null && carerInfoFrag.isVisible()) { 

        Log.e(TAG, "CarerInfoFragment is visible"); 


        FragmentTransaction transaction = getFragmentManager().beginTransaction(); 

        // Replace whatever is in the fragment_container view with this fragment, 
        // and add the transaction to the back stack 
        transaction.remove(carerInfoFrag); 
        //transaction.addToBackStack(null); 

        // Commit the transaction 
        transaction.commit(); 
       } 


     now = new DateTime(); 
     //now.minusDays(14); 
     DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y"); 
     String formattedNow = fmt.print(now); 





     View CarerDetailsInfoFragContainer = (View)findViewById(R.id.carerdetailsinfofragment_container); 

     if (CarerDetailsInfoFragContainer == null) { 

      Intent intent = new Intent(this, DisplayCarerDetailsfragmentActivity.class); 
      intent.putExtra("carerid", carerId); 
      intent.putExtra("date", formattedNow); 

      startActivity(intent); 


      } else { 
      // DisplayFragment (Fragment B) is in the layout (tablet layout), 
      // so tell the fragment to update 

       String[] params = new String[] { carerId, formattedNow }; 
       AsyncGetRota agr = new AsyncGetRota(); 
       agr.execute(params); 



      } 

      }else{ 

       View CarerDetailsInfoFragContainer = (View)findViewById(R.id.carerdetailsinfofragment_container); 

       if (CarerDetailsInfoFragContainer == null) { 


        Intent intent = new Intent(this, DisplayCarerInfofragmentActivity.class); 
        startActivity(intent); 




       }else{ 

       Fragment newFragment = new CarerInfoFragment(); 


       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.carerdetailsinfofragment_container, newFragment); 
       //transaction.addToBackStack(null); 

       // Commit the transaction 
       transaction.commit(); 


       } 



      } 






    }//end of onArticleSelected 








    private class AsyncGetRota extends AsyncTask<String, Void, TwoDimensionalArrayList<String>> { 


      TwoDimensionalArrayList rotaArray; 
      ProgressDialog progressDialog; 
      String carerID = null; 
      String date = null; 


      @Override 
      protected void onPreExecute() { 




       progressDialog = new ProgressDialog(OnCallListAndDetailsActivity.this); 
       progressDialog.setTitle("Connecting to Server"); 
       progressDialog.setMessage("retrieving rota..."); 
       progressDialog.setIndeterminate(true); 
       progressDialog.show(); 

      } 



      @Override 
      protected TwoDimensionalArrayList<String> doInBackground(String... params) { 

       try { 

        carerID = params[0]; 
        date = params[1]; 


        Log.e(TAG, "now in doinbackground = " + params[1]); 
        rotaArray = rrOnCallApp.webService.getCarerRota(params[0], params[1]); 

        if (rotaArray == null) { 
         Log.e(TAG, "about to call onstart"); 

        } 

       } catch (Exception e) { 

        e.printStackTrace(); 

       } 
       return rotaArray; 

      }//end of doInBackground 



      @Override 
      protected void onPostExecute(TwoDimensionalArrayList<String> result) { 
       super.onPostExecute(result); 
       if (progressDialog != null) 
        progressDialog.dismiss(); 



       if (result == null) { 

        Log.e(TAG, "rotaArray in onPostExecute OnCallListAndDetailsActivity = null"); 

       } else { 




        Log.e(TAG, "rotaArray in onPostExecute OnCallListAndDetailsActivity has size " + rotaArray.size()); 
        Bundle b = new Bundle(); 
        b.putSerializable("rotaArray", rotaArray); 
        b.putString("carerid", carerID); 
        b.putString("date", date); 

        Fragment newFragment = new CarerDetailsFragment(); 
        newFragment.setArguments(b); 

        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.carerdetailsinfofragment_container, newFragment); 
        //transaction.addToBackStack(null); 

        // Commit the transaction 
        transaction.commit(); 


        OnCallListAndDetailsActivity.this.invalidateOptionsMenu(); 





       } 

      }//end of onPostExecute 

    } 








// @Override 
// public void onRotaButtonSelected(String action, String date, String carerid) { 
//  
//  CarerPurposeOfCallFragment test = (CarerPurposeOfCallFragment) getFragmentManager().findFragmentById(R.id.carerpurposeofcallfragment_container); 
//  if (test != null && test.isVisible()) { 
//   
//   Log.e(TAG, "CarerPurposeOfCallFragment is visible"); 
//   
//   
//   FragmentTransaction transaction = getFragmentManager().beginTransaction(); 
// 
//   // Replace whatever is in the fragment_container view with this fragment, 
//   // and add the transaction to the back stack 
//   transaction.remove(test); 
//   //transaction.addToBackStack(null); 
// 
//   // Commit the transaction 
//   transaction.commit(); 
//  } 
//  
//  if(action.equalsIgnoreCase("next")){ 
//   
//   Log.e(TAG, "next clicked and date passed in is " + date); 
//   
//   now = now.plusDays(1); 
//   
//   DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y"); 
//   String formattedNow = fmt.print(now); 
//   
//   getRota(formattedNow, carerid); 
//   
//   
//   
//  
//  }else if(action.equalsIgnoreCase("previous")){ 
//   
//   Log.e(TAG, "previous clicked"); 
//   
//   now = now.minusDays(1); 
//   
//   DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y"); 
//   String formattedNow = fmt.print(now); 
//   
//   getRota(formattedNow, carerid); 
//   
//  }else if(action.equalsIgnoreCase("pickday")){ 
//   
//   Log.e(TAG, "pickday clicked"); 
//   
//   loadDatePicker(); 
//   
//   
//  } 
//  
// }//end of onRotaButtonSelected 



    public void getRota(String date, String carerid){ 


     View CarerDetailsInfoFragContainer = (View)findViewById(R.id.carerdetailsinfofragment_container); 

     if (CarerDetailsInfoFragContainer == null) { 

      Intent intent = new Intent(this, DisplayCarerDetailsfragmentActivity.class); 
      intent.putExtra("carerid", carerid); 
      intent.putExtra("date", date); 

      startActivity(intent); 


      } else { 
      // DisplayFragment (Fragment B) is in the layout (tablet layout), 
      // so tell the fragment to update 

       String[] params = new String[] { carerid, date }; 
       AsyncGetRota agr = new AsyncGetRota(); 
       agr.execute(params); 

      } 


    }//getRota 



    public void loadDatePicker(){ 

     Fragment newFragment = new RotaDatePicker(); 


     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.carerdetailsinfofragment_container, newFragment); 
     //transaction.addToBackStack(null); 

     // Commit the transaction 
     transaction.commit(); 


    } 




    @Override 
    public void onRotaDateSelected(DateTime date) { 

     //set now so when the user clicks next/previous after pickDay has been pressed the datatime is remembered 
     //eg 24->25->29->28 
     //not 24->25->29->24 
     now = date; 

     DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y"); 
     String formattedNow = fmt.print(date); 

     getRota(formattedNow, mCarerID); 


    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu items for use in the action bar 
     MenuInflater inflater = getMenuInflater(); 
     inflater.inflate(R.menu.rotamenu, menu); 
     return super.onCreateOptionsMenu(menu); 
    } 




    @Override 
    public boolean onMenuItemSelected(int featureId, MenuItem item) { 


     CarerPurposeOfCallFragment test = (CarerPurposeOfCallFragment) getFragmentManager().findFragmentById(R.id.carerpurposeofcallfragment_container); 
     if (test != null && test.isVisible()) { 

      Log.e(TAG, "CarerPurposeOfCallFragment is visible"); 


      FragmentTransaction transaction = getFragmentManager().beginTransaction(); 

      // Replace whatever is in the fragment_container view with this fragment, 
      // and add the transaction to the back stack 
      transaction.remove(test); 
      //transaction.addToBackStack(null); 

      // Commit the transaction 
      transaction.commit(); 
     } 




     switch (item.getItemId()) { 

     case R.id.previous: 

      Log.e(TAG, "previous clicked"); 

      if(now != null){ 

      now = now.minusDays(1); 

      DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y"); 
      String formattedNow = fmt.print(now); 

      getRota(formattedNow, mCarerID); 

      }else{ 
       Log.e(TAG, "now is null"); 
      } 

      return true; 


     case R.id.next: 

      Log.e(TAG, "next clicked"); 

      if(now != null){ 
      now = now.plusDays(1); 

      DateTimeFormatter fmt2 = DateTimeFormat.forPattern("d-MMM-Y"); 
      String formattedNow2 = fmt2.print(now); 

      getRota(formattedNow2, mCarerID); 
      }else{ 
       Log.e(TAG, "now is null"); 
      } 

      return true; 


     case R.id.pickaday: 

      Log.e(TAG, "pickday clicked"); 

      if(mCarerID != null){ 

      loadDatePicker(); 
      } 

      return true; 

     case R.id.updatecall2: 

      Log.e(TAG, "update call clicked"); 

      if(mCarerID != null){ 

      ContentValues cv = ((CarerDetailsFragment) getFragmentManager().findFragmentById(R.id.carerdetailsinfofragment_container)).getCallParams(); 

      callStartTime = cv.getAsString("callstarttime"); 
      callDuration = cv.getAsString("callduration"); 
      callID = cv.getAsString("callid"); 

      if(callStartTime == null || callDuration == null || callID == null){ 


       AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); 

        // set title 
        alertDialogBuilder.setTitle("No Call Selected!"); 

        // set dialog message 
        alertDialogBuilder 
          .setMessage(
            "Please Select a call from the rota to update.") 
          .setCancelable(false) 
          .setPositiveButton("OK", 
            new DialogInterface.OnClickListener() { 
             public void onClick(DialogInterface dialog, int id) { 


             } 
            }); 

        // create alert dialog 
        AlertDialog alertDialog = alertDialogBuilder.create(); 

        // show it 
        alertDialog.show(); 




      }else{ 

      CarerListFragment carerListFrag = (CarerListFragment) getFragmentManager().findFragmentById(R.id.carerlist); 

       if (carerListFrag != null && carerListFrag.isVisible()) { 

        DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y"); 
        String date = fmt.print(now); 

       Intent updateCall = new Intent(this, UpdateCallDateTimeAndCarerActivity.class); 
       updateCall.putExtra("callstarttime", callStartTime); 
       updateCall.putExtra("callid", callID); 
       updateCall.putExtra("callduration", callDuration); 
       updateCall.putExtra("carerid", mCarerID); 
       updateCall.putExtra("rotadate", date); 


       startActivity(updateCall); 

       }else{ 

        Log.e(TAG, "must be on a phone!"); 

        DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y"); 
        String date = fmt.print(now); 

        Intent updateCallOnPhone = new Intent(this, UpdateCallDateTimeActivity.class); 
        updateCallOnPhone.putExtra("callstarttime", callStartTime); 
        updateCallOnPhone.putExtra("callid", callID); 
        updateCallOnPhone.putExtra("callduration", callDuration); 
        updateCallOnPhone.putExtra("carerid", mCarerID); 
        updateCallOnPhone.putExtra("rotadate", date); 

        startActivity(updateCallOnPhone); 

       } 


      } 



      }else{ 

       AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); 

       // set title 
       alertDialogBuilder.setTitle("No Carer Selected!"); 

       // set dialog message 
       alertDialogBuilder 
         .setMessage(
           "Please Select a carer from the carer list.") 
         .setCancelable(false) 
         .setPositiveButton("OK", 
           new DialogInterface.OnClickListener() { 
            public void onClick(DialogInterface dialog, int id) { 


            } 
           }); 

       // create alert dialog 
       AlertDialog alertDialog = alertDialogBuilder.create(); 

       // show it 
       alertDialog.show(); 

      } 

      return true; 





     } 

     return super.onMenuItemSelected(featureId, item); 
    } 

    @Override 
    public boolean onPrepareOptionsMenu(Menu menu) { 
     super.onPrepareOptionsMenu(menu); 

     CarerDetailsFragment test2 = (CarerDetailsFragment) getFragmentManager().findFragmentById(R.id.carerdetailsinfofragment_container); 
     if (test2 == null ) { 

      Log.e(TAG, "CarerDetailsFragment = not visible"); 

     menu.getItem(0).setVisible(false); 
     menu.getItem(1).setVisible(false); 
     menu.getItem(2).setVisible(false); 

    }else{ 
     Log.e(TAG, "CarerDetailsFragment = visible"); 
     menu.getItem(0).setVisible(true); 
     menu.getItem(1).setVisible(true); 
     menu.getItem(2).setVisible(true); 
    } 

    // add your conditions here and change 0 with the R.id.moredetails item postion. 
     CarerPurposeOfCallFragment test = (CarerPurposeOfCallFragment) getFragmentManager().findFragmentById(R.id.carerpurposeofcallfragment_container); 
     if (test == null || ! test.isVisible()) { 

     menu.getItem(3).setVisible(false); 

    }else{ 

     menu.getItem(3).setVisible(true); 
    } 




    return true; 

    }//end of onPrepareOptionsMenu 


}//end of class 

回答

0

解決

代替在活動從onPostExecute主叫invalidateOptionsMenu,我請

getActivity().invalidateOptionsMenu(); 

在片段I類放在它裏面onActivityCreated();

現在工作正常。

馬特