如何更新导航抽屉中的未读通知计数器?

How do I update unread notification counter in the Navigation Drawer?

我目前正在开发一个应用程序,它将有一个包含 2 个部分的通知抽屉 -

  1. 状态请求的 仪表板(待定、已提交、处理中、已完成)。我把它命名为DashboardFragment.java
  2. 一个通知中心显示从第3方Java服务器(通过Google云消息服务器)收到的所有消息。我把它命名为PushMessagesFragment.java

我面临的问题是,当我从服务器收到通知时,一旦我打开 PushMessages 片段,"unread messages" 计数不会重置为零。

此外,未读消息计数仅在我单击通知时更新;而即使我只是打开导航抽屉,它也应该更新(并显示未读消息的数量)。

这是截图 -

http://i.imgur.com/hSM9Fxm.png "Unread Message Count Not Updated"

对于 Navigation Drawer,我使用的模型 Class 名为 NavDrawerItem.java,它具有以下代码 -

public class NavDrawerItem {

private String title;
private int icon;
private String count = "0";

// boolean to set visiblity of the counter
private boolean isCounterVisible = false;

public NavDrawerItem(String title, int icon) {
    this.title = title;
    this.icon = icon;
}

public NavDrawerItem(String title, int icon, boolean isCounterVisible, String count) {
    this.title = title;
    this.icon = icon;
    this.isCounterVisible = isCounterVisible;
    this.count = count;
}

public String getTitle() {
    return this.title;
}

public int getIcon() {
    return this.icon;
}

public String getCount() {
    return this.count;
}

public boolean getCounterVisibility() {
    return this.isCounterVisible;
}

public void setTitle(String title) {
    this.title = title;
}

public void setIcon(int icon) {
    this.icon = icon;
}

public void setCount(String count) {
    this.count = count;
}

public void setCounterVisibility(boolean isCounterVisible) {
    this.isCounterVisible = isCounterVisible;
}

}

我正在为我的导航抽屉使用名为 NavigationDrawerListAdapter 的自定义适配器。

public class NavigationDrawerListAdapter extends BaseAdapter {
   private Context context;
   private ArrayList < NavDrawerItem > navDrawerItems;
   public NavigationDrawerListAdapter(Context context, ArrayList < NavDrawerItem > navDrawerItems) {
       this.context = context;
       this.navDrawerItems = navDrawerItems;
   }@
   Override
   public int getCount() {
       return navDrawerItems.size();
   }@
   Override
   public Object getItem(int position) {
       return navDrawerItems.get(position);
   }@
   Override
   public long getItemId(int position) {
       return position;
   }@
   Override
   public View getView(int position, View convertView, ViewGroup parent) {
       NavDrawerViewHolder viewHolder;
       if (convertView == null) {
           viewHolder = new NavDrawerViewHolder();
           LayoutInflater mInflater = (LayoutInflater)
           context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
           convertView = mInflater.inflate(R.layout.nav_drawer_list_item, null);
           viewHolder.imgIcon = (ImageView) convertView.findViewById(R.id.icon);
           viewHolder.txtTitle = (TextView) convertView.findViewById(R.id.title);
           viewHolder.txtCount = (TextView) convertView.findViewById(R.id.counter);
           convertView.setTag(viewHolder);
       } else {
           // Get the ViewHolder back to get fast access to the TextView
           // and the ImageView.
           viewHolder = (NavDrawerViewHolder) convertView.getTag();
       }
       viewHolder.imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
       viewHolder.txtTitle.setText(navDrawerItems.get(position).getTitle());
       // displaying count
       // check whether it set visible or not
       if (navDrawerItems.get(position).getCounterVisibility()) {
           viewHolder.txtCount.setText(navDrawerItems.get(position).getCount());
       } else {
           // hide the counter view
           viewHolder.txtCount.setVisibility(View.GONE);
       }
       return convertView;
   }
   static class NavDrawerViewHolder {
       ImageView imgIcon;
       TextView txtTitle;
       TextView txtCount;
   }

}

这里是 NavigationDrawerFragment 片段的代码,它扩展了自定义列表布局并将自定义适配器附加到导航抽屉的 ListView。

public class NavigationDrawerFragment extends Fragment {

UserSessionManager session;
ShareBlankRegIDWithServer appUtilBlank ;
AsyncTask shareNARegidTask;
String regId;

Button notifCount;
static int mNotifCount = 0;

public int NOTIFICATION_ID;
/**
 * Remember the position of the selected item.
 */
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

/**
 * Per the design guidelines, you should show the drawer on launch until the user manually
 * expands it. This shared preference tracks this.
 */
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

/**
 * A pointer to the current callbacks instance (the Activity).
 */
private NavigationDrawerCallbacks mCallbacks;

/**
 * Helper component that ties the action bar to the navigation drawer.
 */
private ActionBarDrawerToggle mDrawerToggle;

// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;

//import Model class and Adapter Class for Navigation Drawer Items
private ArrayList<NavDrawerItem> navDrawerItems;
private NavigationDrawerListAdapter adapter;

private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;

private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;

public NavigationDrawerFragment() {
}

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

    // Read in the flag indicating whether or not the user has demonstrated awareness of the
    // drawer. See PREF_USER_LEARNED_DRAWER for details.
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

    if (savedInstanceState != null) {
        mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
        mFromSavedInstanceState = true;
    }

    // Select either the default item (0) or the last selected item.
    selectItem(mCurrentSelectedPosition);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // Indicate that this fragment would like to influence the set of actions in the action bar.
    setHasOptionsMenu(true);
}

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

    //get value of current Notification_ID
    NOTIFICATION_ID = NotificationID.getID();

    // Create an Instance of User Session Manager
    session = new UserSessionManager(getActivity().getApplicationContext());

    // load slide menu items
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    // nav drawer icons from resources
    navMenuIcons = getResources()
            .obtainTypedArray(R.array.nav_drawer_icons);

    mDrawerListView = (ListView) inflater.inflate(
            R.layout.fragment_navigation_drawer, container, false);

    mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    });

    navDrawerItems = new ArrayList<NavDrawerItem>();

    // adding nav drawer items to array
    // Dashboard (with a counter)
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
    // Notification Center (with a counter)
//this is where I am setting the Notification ID to the list item with the counter i.e. Notification Center
    navDrawerItems.add(new NavDrawerItem(
            navMenuTitles[1],
            navMenuIcons.getResourceId(1, -1),
            true,
            String.valueOf(NOTIFICATION_ID)));

    // Download Reports (without a counter)
    // navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));


    // Recycle the typed array
    navMenuIcons.recycle();

    // setting the nav drawer list adapter
    adapter = new NavigationDrawerListAdapter(getActivity().getApplicationContext(),
            navDrawerItems);

    //set adapter
    mDrawerListView.setAdapter(adapter);

    mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
    return mDrawerListView;
}

public boolean isDrawerOpen() {
    return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}

/**
 * Users of this fragment must call this method to set up the navigation drawer interactions.
 *
 * @param fragmentId   The android:id of this fragment in its activity's layout.
 * @param drawerLayout The DrawerLayout containing this fragment's UI.
 */
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
    mFragmentContainerView = getActivity().findViewById(fragmentId);
    mDrawerLayout = drawerLayout;

    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the navigation drawer and the action bar app icon.
    mDrawerToggle = new ActionBarDrawerToggle(
            getActivity(),                    /* host Activity */
            mDrawerLayout,                    /* DrawerLayout object */
            R.drawable.ic_drawer,             /* nav drawer image to replace 'Up' caret */
            R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
            R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
    ) {
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            Log.e("Drawer", "Closed");
            if (!isAdded()) {
                return;
            }

            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            Log.e("Drawer","Opened");
            if (!isAdded()) {
                return;
            }

            if (!mUserLearnedDrawer) {
                // The user manually opened the drawer; store this flag to prevent auto-showing
                // the navigation drawer automatically in the future.
                mUserLearnedDrawer = true;
                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(getActivity());
                sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).commit();
            }

            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }
    };

    // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
    // per the navigation drawer design guidelines.
    if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
        mDrawerLayout.openDrawer(mFragmentContainerView);
    }

    // Defer code dependent on restoration of previous instance state.
    mDrawerLayout.post(new Runnable() {
        @Override
        public void run() {
            mDrawerToggle.syncState();
        }
    });

    mDrawerLayout.setDrawerListener(mDrawerToggle);
}

private void selectItem(int position) {
    mCurrentSelectedPosition = position;
    if (mDrawerListView != null) {
        mDrawerListView.setItemChecked(position, true);
    }
    if (mDrawerLayout != null) {
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }
    if (mCallbacks != null) {
        mCallbacks.onNavigationDrawerItemSelected(position);
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mCallbacks = (NavigationDrawerCallbacks) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mCallbacks = null;
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Forward the new configuration the drawer toggle component.
    mDrawerToggle.onConfigurationChanged(newConfig);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // If the drawer is open, show the global app actions in the action bar. See also
    // showGlobalContextActionBar, which controls the top-left area of the action bar.
    if (mDrawerLayout != null && isDrawerOpen()) {
        inflater.inflate(R.menu.global, menu);

        Log.d("Drawer Open", "Menu global Inflated");

        showGlobalContextActionBar();
        adapter.notifyDataSetChanged();
        Log.e("NavDrawerFragment", "notifyDataSetChanged");
    }
    super.onCreateOptionsMenu(menu, inflater);
}

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

    if (item.getItemId() == R.id.action_logout) {
        //ask if user really wants to sign out
        // if yes then ->
        // Clear the User session data
        // and redirect user to LoginActivity


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

        // set title
        alertDialogBuilder.setTitle("Quit");

        // set dialog message
        alertDialogBuilder
                .setMessage("Do you really wish to logout ?")
                .setCancelable(false)
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, close
                        // current activity
                        appUtilBlank = new ShareBlankRegIDWithServer();
                        shareNARegidTask = new MyAsyncClass().execute(null, null, null);


                        //Toast.makeText(getActivity().getApplicationContext(), "Signing Out", Toast.LENGTH_SHORT).show();

                        //finish MainActivity to NOT make the users go back to Dashboard upon pressing BACK button
                        Intent launchNextActivity;
                        launchNextActivity = new Intent(getActivity(), LoginActivity.class);
                        launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        startActivity(launchNextActivity);


                        //clear User Detail SharedPrefs
                        session.logoutUser();
                        Log.d("CLEARED", "Preferences");





                    }
                })
                .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

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

        // show it
        alertDialog.show();

        return true;

    }

    return super.onOptionsItemSelected(item);
}

/**
 * Per the navigation drawer design guidelines, updates the action bar to show the global app
 * 'context', rather than just what's in the current screen.
 */
private void showGlobalContextActionBar() {
    ActionBar actionBar = getActionBar();
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setTitle(R.string.app_name);
}

private ActionBar getActionBar() {
    return ((ActionBarActivity) getActivity()).getSupportActionBar();
}

/**
 * Callbacks interface that all activities using this fragment must implement.
 */
public static interface NavigationDrawerCallbacks {
    /**
     * Called when an item in the navigation drawer is selected.
     */
    void onNavigationDrawerItemSelected(int position);
}

public class MyAsyncClass extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        Log.d("NavigationDrawerFragment doInBackround", "share Blank RegId with Server");
        //get RegID from SharedPrefs
        //regId = new RegisterInBackground(getActivity().getApplicationContext()).getRegistrationId(getActivity().getApplicationContext());

        String result = appUtilBlank.shareBlankRegIdWithAppServer(getActivity().getApplicationContext(), regId);

        return result;
    }

    @Override
    protected void onPostExecute(String result) {


        //Toast.makeText(getApplicationContext(), result,Toast.LENGTH_LONG).show();
    }


}

}

终于得到了我想要的结果

首先,我更改了 NavigationDrawerListAdapter 中的 setText() 值。

if (navDrawerItems.get(position).getCounterVisibility()) {
    //viewHolder.txtCount.setText(navDrawerItems.get(position).getCount());
 //The next line is where I made the change
    viewHolder.txtCount.setText(String.valueOf(NotificationID.getID()));
    Log.e("Counter Value set to", String.valueOf(NotificationID.getID()));
}

然后,在我的 Singleton class NotificationID 中,我将 setZero() 方法体从

public static int setToZero() 
{
  return 0;
}

public static int setToZero() 
{
  c = 0;
  return c;
}

我所做的最后更改是 PushMessagesFragment.java,因为我想在每次打开该片段时将计数器重置为零。

//set notification id to zero
NOTIFICATION_ID = NotificationID.setToZero();
//NOTIFICATION_ID = NotificationID.setID();
Log.e("Push Messages NOTIFICATION_ID", String.valueOf(NotificationID.getID()));

现在我的应用似乎运行良好,在我收到消息时显示实际通知计数,在我打开 PushMessage Fragment 时显示零计数。