我目前正在开发app,它将有一个包含2个部分的通知抽屉 -
我面临的问题是,当我收到来自服务器的通知时,"未读消息"打开 PushMessages Fragment 后,count不会重置为零。
此外,单击通知时,仅更新未读消息计数;而它应该更新(并显示未读消息数量的计数),即使我只是打开导航抽屉。
这是截图 -
http://i.imgur.com/hSM9Fxm.png"未读消息计数未更新"
对于导航抽屉,我使用名为 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 for Navigation Drawer。
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();
}
}
}
答案 0 :(得分:0)
最后,我设法得到了我想要的结果。
首先,我更改了 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类 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时显示ZERO计数。