加载片段后,android刷新OptionsMenu

时间:2014-04-29 13:26:04

标签: android fragment android-optionsmenu

我有一个使用Fragments的应用。它在视图中有3个片段。最左边的片段是护理者列表。中间片段是另一个列表,它是一个看护者rota。

当加载主屏幕(包含所有3个片段的Activity)时,仅加载左片段。如果你选择一个看护人,则加载中间片段(rota)。

问题是用户可以从optionsMenu中选择next,previous等来为给定的护理者选择下一天或前一天的rota。如果当前没有显示rota(中间片段),我不希望optionsMenu显示下一个或上一个按钮。

每个rota都是从AsyncTask加载的。在onPostExecute中,我加载了carerdetailsFragment,它是rota。我已经覆盖了onPrepareOptionsMenu并在那里检查了是否显示了rota。在获得rota之后,我还从onPostExecute调用了invalidateOptionsMenu。

当仅显示左侧片段时,optionsMenu会首先隐藏按钮,但是当您获得旋转时,它不会更新选项菜单,直到您再次加载旋转。

为什么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

1 个答案:

答案 0 :(得分:1)

解决

而不是从活动中的onPostExecute调用invalidateOptionsMenu,我打电话

getActivity().invalidateOptionsMenu();

在Fragment类中,我把它放在onActivityCreated();

现在工作正常。

马特