How to close navigation drawer smoothly when selecting new activity? - android

I have implemented the material design navigation drawer. However when selecting a new activity the navigation drawer doesn't close smoothly. (I have tried various solutions and suggestions here on SO, but nothing actually helps me)
So I am hoping someone has found a solution to this?
Here is my MainActivity.class:
public class MainActivity extends ActionBarActivity
implements NavigationDrawerCallbacks {
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
private boolean doubleBackToExitPressedOnce;
private ProgressDialog pd = null;
private Object data = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
// populate the navigation drawer
mNavigationDrawerFragment.setUserData("WELCOME", "", BitmapFactory.decodeResource(getResources(), R.drawable.ic_avatar));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FragmentHome();
break;
case 1:
fragment = new FragmentSecondActivity();
break;
case 2:
fragment = new FragmentThirdActivity();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).commit();
}
}
#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);
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);
}
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please press BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
NavigationDrawerFragment:
public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private DrawerLayout mDrawerLayout;
private RecyclerView mDrawerList;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition);
return view;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public ActionBarDrawerToggle getActionBarDrawerToggle() {
return mActionBarDrawerToggle;
}
public DrawerLayout getDrawerLayout() {
return mDrawerLayout;
}
#Override
public void onNavigationDrawerItemSelected(int position) {
selectItem(position);
}
public List<NavigationItem> getMenu() {
List<NavigationItem> items = new ArrayList<NavigationItem>();
items.add(new NavigationItem("Home", getResources().getDrawable(R.drawable.ic_home)));
items.add(new NavigationItem("Second Activity", getResources().getDrawable(R.drawable.ic_icon)));
items.add(new NavigationItem("Third Activity", getResources().getDrawable(R.drawable.ic_icon)));
return items;
}
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.myPrimaryDarkColor));
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) return;
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mActionBarDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}
public void openDrawer() {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
public void closeDrawer() {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
#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.
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
public void setUserData(String user, String email, Bitmap avatar) {
ImageView avatarContainer = (ImageView) mFragmentContainerView.findViewById(R.id.imgAvatar);
((TextView) mFragmentContainerView.findViewById(R.id.txtUserEmail)).setText(email);
((TextView) mFragmentContainerView.findViewById(R.id.txtUsername)).setText(user);
avatarContainer.setImageDrawable(new RoundImage(avatar));
}
public View getGoogleDrawer() {
return mFragmentContainerView.findViewById(R.id.googleDrawer);
}
public static class RoundImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;
public RoundImage(Bitmap bitmap) {
mBitmap = bitmap;
mRectF = new RectF();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
canvas.drawOval(mRectF, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
#Override
public void setAlpha(int alpha) {
if (mPaint.getAlpha() != alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
#Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
public void setAntiAlias(boolean aa) {
mPaint.setAntiAlias(aa);
invalidateSelf();
}
#Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
#Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
public Bitmap getBitmap() {
return mBitmap;
}
}
}
What can I do to make closing the navigation drawer close smoothly? At the moment it closes halfway then stops for a second then closes and the new activity is shown.

add the below method before calling another class on navigation drawer item click i.e. in onnavigationdrawerselected method
mNavigationDrawerFragment.closeDrawers();
This will close the navigation drawer..

close your drawer first.
after 200ms, open your new activity

USE A THREAD TO CLOSE THE DRAWER THAT CAN IMPROVE SOME CASES
new Handler().post(new Runnable() {
#Override
public void run() {
drawerLayout.closeDrawers();
}
});

Related

add slider menu in navigation drawer

I want to add slider down menu in Navigation Drawer like this.
After click left side icon, it shows like this.
What can be done for this ?
This is Navigation Drawer with ExpandableListview
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private String[] items;
private ExpandableListView mExpandableListView;
private ExpandableListAdapter mExpandableListAdapter;
private List<String> mExpandableListTitle;
private NavigationManager mNavigationManager;
private Map<String, List<String>> mExpandableListData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
mExpandableListView = (ExpandableListView) findViewById(R.id.navList);
mNavigationManager = FragmentNavigationManager.obtain(this);
initItems();
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.nav_header, null, false);
mExpandableListView.addHeaderView(listHeaderView);
mExpandableListData = ExpandableListDataSource.getData(this);
mExpandableListTitle = new ArrayList(mExpandableListData.keySet());
addDrawerItems();
setupDrawer();
if (savedInstanceState == null) {
selectFirstItemAsDefault();
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void selectFirstItemAsDefault() {
if (mNavigationManager != null) {
String firstActionMovie = getResources().getStringArray(R.array.actionFilms)[0];
mNavigationManager.showFragmentAction(firstActionMovie);
getSupportActionBar().setTitle(firstActionMovie);
}
}
private void initItems() {
items = getResources().getStringArray(R.array.film_genre);
}
private void addDrawerItems() {
mExpandableListAdapter = new CustomExpandableListAdapter(this, mExpandableListTitle, mExpandableListData);
mExpandableListView.setAdapter(mExpandableListAdapter);
mExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
getSupportActionBar().setTitle(mExpandableListTitle.get(groupPosition).toString());
}
});
mExpandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
getSupportActionBar().setTitle(R.string.film_genres);
}
});
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String selectedItem = ((List) (mExpandableListData.get(mExpandableListTitle.get(groupPosition))))
.get(childPosition).toString();
getSupportActionBar().setTitle(selectedItem);
if (items[0].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentAction(selectedItem);
} else if (items[1].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentComedy(selectedItem);
} else if (items[2].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentDrama(selectedItem);
} else if (items[3].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentMusical(selectedItem);
} else if (items[4].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentThriller(selectedItem);
} else {
throw new IllegalArgumentException("Not supported fragment type");
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(R.string.film_genres);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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();
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
For more see this https://github.com/msahakyan/expandable-navigation-drawer

NavigationDrawer not show the view

I have a Navigation Drawer with Navigation View, there are four tabs, one of them is a fragment, which includes ViewPager, ie is a host for the other fragments. Everything works fine, but when switched from fragment with ViewPager any other fragment of NavigationDrawer shows nothing. Checked logs, onCreate, onCreateView these fragments are called, but why does not display... Who knows why?
NavigationDrawer
public class NavigationDrawerHost extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
//буду использовать эту активность как хост под все фрагменты, чтобы верно работал мой drawer!
public static String WHERE_FROM = NavigationDrawerHost.class.getSimpleName();
public static Toolbar toolbar;
public static ProgressBar progressBar;
private DrawerLayout drawer;
private NavigationView navigationView;
private ActionBarDrawerToggle drawerToggle;
private int navItemId;
private static final String NAV_ITEM_ID = "NAV_ITEM_ID";
private TextView userFirstNameTextView, userLastNameTextView;
private ImageView userPhotoImageView;
private VKAccessToken access_token; //токен это информация о правах доступа
private VKApiUser user; //текущий пользователь
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer_host);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// Find the toolbar view inside the activity layout
toolbar = (Toolbar) findViewById(R.id.toolbar);
// Set a Toolbar to replace the ActionBar.
setSupportActionBar(toolbar);
//setTitle(R.string.drawer_menu_posts);
// load saved navigation state if present
if (null == savedInstanceState) {
navItemId = R.id.posts_fragment;
} else {
navItemId = savedInstanceState.getInt(NAV_ITEM_ID);
}
// Find our drawer view
navigationView = (NavigationView) findViewById(R.id.nvView);
navigationView.setNavigationItemSelectedListener(this);
// select the correct nav menu item
navigationView.getMenu().findItem(navItemId).setChecked(true);
// если хотим добавить какие-то элементы в наш header,
// то нужно добавить их в layout, а затем инициализировать нижеприведенным способом
// Inflate the header view at runtime
View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header);
// We can now look up items within the header if needed
userFirstNameTextView = (TextView) headerLayout.findViewById(R.id.user_first_name);
userLastNameTextView = (TextView) headerLayout.findViewById(R.id.user_last_name);
userPhotoImageView = (ImageView) headerLayout.findViewById(R.id.user_photo);
drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close);
// Tie DrawerLayout events to the ActionBarToggle
drawer.setDrawerListener(drawerToggle);
drawerToggle.syncState();
selectItem(navItemId);
}
#Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(NAV_ITEM_ID, navItemId);
}
// Menu icons are inflated just as they were with actionbar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_exit:
//quitDialog();
VKSdk.logout();
finish();
return true;
default:
return drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
}
// Make sure this is the method with just `Bundle` as the signature
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(final int itemId) {
// perform the actual navigation logic, updating the main content fragment etc
// Create a new fragment and specify the planet to show based on position
Fragment fragment = null;
Class fragmentClass = null;
switch (itemId) {
case R.id.posts_fragment:
fragmentClass = PostsFragment.class;
fragment = new PostsFragment();
break;
case R.id.albums_fragment:
fragmentClass = FragmentTest.class;
fragment = new FragmentTest();
break;
case R.id.friends_fragment:
fragmentClass = FragmentTest.class;
fragment = new FragmentTest();
break;
case R.id.likes_fragment:
fragmentClass = LikesFragment.class;
fragment = new LikesFragment();
break;
/*default:
fragmentClass = PostsFragment.class;*/
}
/*try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}*/
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
drawer.closeDrawers();
}
#Override
public boolean onNavigationItemSelected(final MenuItem item) {
// update highlighted item in the navigation menu
item.setChecked(true);
setTitle(item.getTitle());
navItemId = item.getItemId();
// allow some time after closing the drawer before performing real navigation
// so the user can see what is happening
drawer.closeDrawer(GravityCompat.START);
selectItem(item.getItemId());
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
quitDialog();
} else {
getSupportFragmentManager().popBackStack();
}
}
private void quitDialog() {
AlertDialog.Builder quitDialog = new AlertDialog.Builder(this);
quitDialog.setTitle("Вы хотите выйти?");
quitDialog.setPositiveButton("Да", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//стираем БД
Delete.tables(PostTable.class, PictureTable.class, PostTableMyLikes.class, PictureTableMyLikes.class);
FlowManager.getDatabase(WallDatabase.DB_NAME).reset(NavigationDrawerHost.this);
FlowManager.getDatabase(WallDatabaseMyLikes.DB_NAME).reset(NavigationDrawerHost.this);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
quitDialog.setNegativeButton("Нет",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
quitDialog.show();
}
}
ViewPager host for fragments, which needs to display through ViewPager
//этот фрагмент является хостом для MyLikesFragment и FriendLikesFragment, так же тут содержатся табы
public class LikesFragment extends Fragment {
public static String WHERE_FROM_FRIENDS_LIKES = LikesFragment.class.getSimpleName() + "_FRIENDSLIKES";
private ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.likes_fragment, container, false);
TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Мои лайки"));
tabLayout.addTab(tabLayout.newTab().setText("Лайки друзей"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) v.findViewById(R.id.view_pager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setAdapter(new LikesPagerAdapter(getChildFragmentManager()));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return v;
}
public static class LikesPagerAdapter extends FragmentPagerAdapter {
public LikesPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
//сделано так, чтобы передавать те аргументы, от которых будет зависеть функционал фрагмента
#Override
public Fragment getItem(int position) {
return (position == 0) ? new MyLikesPostsFragment() : new PostsFragment();
}
#Override
public CharSequence getPageTitle(int position) {
return (position == 0) ? "Мои лайки" : "Лайки друзей";
}
}
}
P.S. And after going to the same fragment ViewPager select several items in drawer, this should not be
The problem was that I called adapter.notifyDataSetChanged() in the main thread and onPostExecute() in AsyncTask. My carelessness...

unable to use handler, getting looper.prepare error

I was trying to use handler in onPageFinished method of onCreateView method of PlanetFragment class. But I am getting looper.prepare() error. Please help. And also please tell if there is some better method to use progressbar.
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
static Handler progressBarHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// 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
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
// view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch (item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available,
Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet,
container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources()
.getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(
planet.toLowerCase(Locale.getDefault()), "drawable",
getActivity().getPackageName());
final WebView webview = ((WebView) rootView
.findViewById(R.id.image));
final ProgressBar progressbar = ((ProgressBar) rootView
.findViewById(R.id.progressbar));
webview.getSettings().setJavaScriptEnabled(true);
final PlanetFragment activity = this;
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
view.setVisibility(View.GONE);// hide the webview that will
// display your dialog
new Thread(new Runnable() {
private int progressBarStatus = 0;
private int fileSize;
public void run() {
progressBarHandler = new Handler();
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doWork();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressbar
.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private int doWork() {
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
} else if (fileSize == 200000) {
return 40;
} else if (fileSize == 300000) {
return 50;
} else if (fileSize == 200000) {
return 60;
} else if (fileSize == 300000) {
return 70;
} else if (fileSize == 200000) {
return 80;
} else if (fileSize == 300000) {
return 90;
}
}
return 100;
}
}).start();
}
#Override
public void onPageFinished(WebView view, String url) {
progressBarHandler = new Handler();
webview.loadUrl("javascript:document.getElementsByClassName('header')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('icon-anon')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('search')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('wh_ad')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('cse_x')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('wh_search')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('wh_ad')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('wh_ad')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('footer_random_button')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('mw-mf-page-left')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('mw-mf-viewport')[0].style.display=\"none\";");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Code here will run in UI thread
}
},1000);
webview.getSettings().setJavaScriptEnabled(false);
view.setVisibility(View.VISIBLE);
// you might need this
view.bringToFront();
}
});
webview.loadUrl(planet);
getActivity().setTitle(planet);
return rootView;
}
}
}
You have to create handler in Activity
just initialize the Handler in onCreate method of activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBarHandler = new Handler();
// rest of your code
and remove the initialization in Fragment class as it is already initialized in Activity . Just Use progressBarHandler in Fragment Class and it will work fine.

How do I add navigation drawer to my existing code?

I have an app in which I have a navigation panel with menu buttons on which I want to apply navigation drawer, currently it takes up the entire screen,but I want to restrict it to 3/4th of the screen by applying navigation drawer on it, but i have never touched navigation drawer before so have no clue, any help or guidance will be great.Also went through some documentation and got confused :(
Here is my code:
and here is my layout class for navigation panel:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res/com.justin.a"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_texture"
android:clickable="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/nav_margin"
android:layout_marginTop="#dimen/nav_margin"
android:layout_marginRight="#dimen/nav_margin"
android:layout_marginBottom="#dimen/nav_margin"
android:background="#242424"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/nav_padding"
android:paddingTop="#dimen/nav_padding"
android:paddingRight="#dimen/nav_padding"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#android:drawable/divider_horizontal_bright"
android:orientation="vertical"
android:showDividers="middle"
>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_dashboard"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:layout_marginBottom="1px"
android:onClick="onDashboardClicked"
android:text="#string/nav_option_dashboard"
android:textSize="#dimen/navigation_panel_text"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_news"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
foo:customFont="cabin.medium.ttf"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
android:onClick="onNewsClicked"
android:text="#string/nav_option_news"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_markets"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
android:onClick="onMarketClicked"
android:text="#string/nav_option_markets"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_lists"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
android:text="#string/nav_option_lists"
foo:customFont="cabin.medium.ttf"
android:onClick="onListsClicked"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<!-- UncommentForAlerts- Remove android:visibility="gone" -->
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_alerts"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:onClick="onAlertsClicked"
android:text="#string/nav_option_alerts"
android:background="#drawable/nav_background_button"
android:visibility="gone"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_briefcase"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:onClick="onBriefcaseClicked"
android:text="#string/nav_option_briefcase"
android:background="#drawable/nav_background_button"
/>
</LinearLayout>
</ScrollView>
<ImageButton
android:id="#+id/button_information"
android:layout_width="#dimen/nav_button"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/nav_padding"
android:layout_centerHorizontal="true"
/>
<ImageButton
android:id="#+id/button_settings"
android:layout_width="#dimen/nav_button"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/nav_padding"
android:layout_toLeftOf="#+id/button_information" />
<ImageButton
android:id="#+id/button_logout"
android:layout_width="#dimen/nav_button"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/nav_padding"
android:layout_toRightOf="#+id/button_information"
/>
</RelativeLayout>
</RelativeLayout>
Also here is my navigationpanelfragment.java:
--UPDATE----
public class NavigationPanelFragment extends Fragment implements OnClickListener {
public static final String TAG_NAVIGATION_PANEL_FRAGMENT = "NavigationPanelFragment";
public static final String ACTIVE_MENU_ITEM = "ActiveMenuItem";
private ActionBarDrawerToggle drawerToggle;
private Fragment lvDrawer;
public static void newInstance(final FragmentManager manager, final String activeFragmentTag) {
final NavigationPanelFragment fragment = new NavigationPanelFragment();
final Bundle arguments = new Bundle();
arguments.putString(NavigationPanelFragment.ACTIVE_MENU_ITEM, activeFragmentTag);
fragment.setArguments(arguments);
final FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD);
fragmentInfo.setAnimation(R.anim.slide_in_from_left, FragmentInfo.NO_ANIMATION);
fragmentInfo.setPopAnimation(0, R.anim.slide_out_to_left);
fragmentInfo.setFragmentTag(TAG_NAVIGATION_PANEL_FRAGMENT);
fragmentInfo.doNotAddToBackStack();
fragmentInfo.setActionBarTitle(Application.getAppResources().getString(R.string.title_applications));
FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);
}
public static void removeInstance(final FragmentManager manager) {
Fragment fragment = manager.findFragmentByTag(TAG_NAVIGATION_PANEL_FRAGMENT);
if (fragment == null) {
return;
}
manager.beginTransaction().setCustomAnimations(0, R.anim.slide_out_to_left).remove(fragment).commitAllowingStateLoss();
}
private LogoutListener mLogoutListener = new LogoutListener() {
#Override
public void onLogoutOperationFired() {
final Activity activity = getActivity();
if(activity != null){
LoginActivity.newInstance(activity);
UserProfileManager.clearUserProfileManager();
FragmentStackManager.getInstance().clearBackStack(getFragmentManager());
activity.finish();
}
}
};
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View view = inflater.inflate(R.layout.fragment_navigation_panel, container, false);
return view;
}
#SuppressWarnings("deprecation")
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ImageButton logoutButton = (ImageButton) getView().findViewById(R.id.button_logout);
logoutButton.setOnClickListener(this);
logoutButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_signout_nav_panel));
final ImageButton infoButton = (ImageButton) getView().findViewById(R.id.button_information);
infoButton.setOnClickListener(this);
infoButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_info_nav_panel));
final ImageButton settingsButton = (ImageButton) getView().findViewById(R.id.button_settings);
settingsButton.setOnClickListener(this);
settingsButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_prefs_nav_panel));
highlightActiveMenuItem();
}
#Override
public void onDestroy() {
super.onDestroy();
mLogoutListener = null;
}
#Override
public void onResume() {
MenuUtils.disableSearchMenu(getActivity());
MenuUtils.disableAlertMenu(getActivity());
super.onResume();
}
#Override
public void onPause() {
MenuUtils.enableSearchMenu(getActivity());
MenuUtils.enableAlertMenu(getActivity());
super.onPause();
}
#Override
public void onClick(final View v) {
switch (v.getId()) {
case R.id.button_logout:
final DialogFragment dialog = new LogoutCancelSignoutDialogFragment(mLogoutListener);
dialog.show(getActivity().getSupportFragmentManager(), AbsBaseaActivity.TAG_LOGOUT_DIALOG);
\ break;
case R.id.button_information:
leaveMainActivity();
InformationActivity.newInstance(getActivity());
\ break;
case R.id.button_settings:
leaveMainActivity();
PreferencesActivity.newInstance(getActivity());
\ break;
}
}
public ActionBarDrawerToggle getDrawerToggle() {
return drawerToggle;
}
private void leaveMainActivity() {
removeInstance(getActivity().getSupportFragmentManager());
final MainActivity activity = (MainActivity) getActivity();
activity.setNavigationOpen(false);
}
private void highlightActiveMenuItem() {
TextView highlightedTextView = null;
final String activeFragmentTitle = "";//getArguments().getString(ACTIVE_MENU_ITEM);
final Resources resources = Application.getAppResources();
if (resources.getString(R.string.nav_option_news).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_news);
} else if (resources.getString(R.string.nav_option_markets).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_markets);
} else if (resources.getString(R.string.nav_option_lists).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_lists);
} else if (resources.getString(R.string.nav_option_alerts).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_alerts);
}
else if (resources.getString(R.string.nav_option_briefcase).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_briefcase);
} else {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_dashboard);
}
highlightedTextView.setTextColor(getResources().getColor(R.color.dark_orange));
}
}
Here is my acitvity_main.xml (it works, shows a blank panel on swipe)
<?xml version="1.0" encoding="utf-8"?>
<!-- <include layout="#layout/main_title"/> -->
<!-- <Button android:text="Main" android:layout_height="wrap_content"
android:id="#+id/btn_refreshbtn_refresh" android:layout_width="wrap_content">
</Button> -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/altercolor2">
</FrameLayout>
<fragment
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:divider="#666"
android:dividerHeight="1dp"
android:background="#333"
android:paddingLeft="15sp"
android:paddingRight="15sp"
android:name="com.justin.jar.fragments.NavigationPanelFragment"/>
</android.support.v4.widget.DrawerLayout>
----UPDATED----
Also here is my mainactivity.java (it has the navigation panel reference which i need to add under navigation drawer):
public class MainActivity extends AbsBaseaActivity implements OnBackStackChangedListener {
public static final int REQUEST_CODE_LIST = 100;
private boolean mIsNavigationOpen = false;
private DrawerLayout drawerLayout;
private NavigationPanelFragment dlDrawer;
private ActionBarDrawerToggle actionBarDrawerToggle;
private boolean mIsSearchBarActive;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
public boolean isNavigationOpen() {
return mIsNavigationOpen;
}
#SuppressWarnings("deprecation")
public void setNavigationOpen(final boolean isNavigationOpen) {
this.mIsNavigationOpen = isNavigationOpen;
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
if(isNavigationOpen) {
mainButton.setBackgroundResource(R.drawable.bg_helios_active);
} else {
mainButton.setBackgroundDrawable(null);
}
}
public static void newInstance(final Activity activity) {
final Intent intent = new Intent(activity, MainActivity.class);
activity.startActivity(intent);
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// 2. App Icon
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// 2.1 create ActionBarDrawerToggle
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.arrow_up, R.string.drawer_open, R.string.drawer_close);
// 2.2 Set actionBarDrawerToggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
initiateMainActionBar();
final FragmentManager supportFragmentManager = getSupportFragmentManager();
supportFragmentManager.addOnBackStackChangedListener(this);
if (savedInstanceState == null) {
mActiveFragment = DashboardFragment.getInstanceWithTransition(supportFragmentManager);
} else {
//resetToDashboard(supportFragmentManager);
}
//setup drawer
/* Set up the drawer toggle */
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.arrow_up, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
getActionBar().setTitle("");
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (dlDrawer.getDrawerToggle().onOptionsItemSelected((android.view.MenuItem) item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
private void setupOnClickListenerForMainButton() {
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
mainButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
toggleNavigationPanel();
}
});
}
#Override
public void manageActionBar() {
setTitle(null);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggleNavigationPanel();
break;
default:
break;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected void onResume() {
final IntentFilter filter = new IntentFilter();
filter.addAction(BroadcastActions.USER_PROFILE);
filter.addAction(BroadcastActions.NEWS_IMAGE);
filter.addAction(BroadcastActions.NEWS_HEADLINES);
registerReceiver(mMainActivityReceiver, filter);
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(mMainActivityReceiver);
super.onPause();
BangoAgent.onIdle();
}
public void pushNewsArticlePagerFragment(final int position, final String selectedCategoryCode, final boolean isMyNews) {
NewsArticlePagerFragment.newInstance(getSupportFragmentManager(), position, selectedCategoryCode, isMyNews);
}
public void onDashboardClicked(final View view) {
toggleNavigationPanel();
if (isFragmentVisible(DashboardFragment.TAG_DASHBOARD_FRAGMENT)) {
return;
}
final FragmentManager manager = getSupportFragmentManager();
final FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = DashboardFragment.getInstance();
transaction.hide(mActiveFragment);
transaction.show(mActiveFragment);
transaction.commitAllowingStateLoss();
updateActionBarTitle();
}
public void onNewsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(NewsFragment.TAG_NEWS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = NewsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onMarketClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(MarketsFragment.TAG_MARKETS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = MarketsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onListsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(ListsContainerFragment.TAG_LIST_CONTAINER_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = ListsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onBriefcaseClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(BriefcaseFragment.TAG_BRIEFCASE_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = BriefcaseFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onAlertsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(AlertsContainerFragment.TAG_ALERTS_CONTAINER_FRAGMENT)){
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = AlertsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
private void toggleNavigationPanel() {
final FragmentStackManager manager = FragmentStackManager.getInstance();
if (mIsNavigationOpen) {
NavigationPanelFragment.removeInstance(getSupportFragmentManager());
updateActionBarTitle();
BangoHelper.eventMainNav();
} else {
final TextView title = (TextView) findViewById(R.id.main_title);
title.setText(getString(R.string.title_applications));
NavigationPanelFragment.newInstance(getSupportFragmentManager(), manager.getTopTitle());
}
setNavigationOpen(!mIsNavigationOpen);
}
public void updateActionBarTitle() {
final String title = FragmentStackManager.getInstance().getTopTitle();
final TextView titleView = (TextView) findViewById(R.id.main_title);
titleView.setText(title);
}
private boolean isFragmentVisible(final String tag) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
return fragment != null && tag.equals(fragment.getTag());
}
public interface BackPressListener<T extends Fragment> {
public boolean backPressed(MainActivity fragmentActivity);
}
private BackPressListener<Fragment> backPressListener = null;
public void setBackPressListener (final BackPressListener<Fragment> backPressListener) {
this.backPressListener = backPressListener;
}
#Override
public void onBackPressed() {
if (backPressListener != null) {
boolean b = false;
// Making sure we trigger the backPressed event if the listener is the top fragment
String bplTag = ((Fragment)backPressListener).getTag();
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
String topFragemtnTag = "";
if (topFragment != null) {
topFragemtnTag = topFragment.getTag();
}
if (mIsSearchBarActive) {
MenuUtils.hideSearchView(this);
mIsSearchBarActive = false;
} else if (mIsNavigationOpen) {
toggleNavigationPanel();
} else if (!FragmentStackManager.getInstance().popTopFragment()) {
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
} else {
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
if (topFragment == null) {
mActiveFragment = DashboardFragment.getInstance();
((DashboardFragment)mActiveFragment).refreshDashboard();
} else if (topFragment instanceof AbsArticlePagerFragment) {
((AbsArticlePagerFragment) topFragment).forceUpdateTextSize();
} else if (topFragment instanceof AbsBaseArticleFragment) {
((AbsBaseArticleFragment) topFragment).forceUpdateTextSize();
}
}
updateActionBarTitle();
}
public void setActiveFragment(final Fragment fragment) {
mActiveFragment = fragment;
}
public void setIsSearchBarActive(final boolean isSearchBarActive){
mIsSearchBarActive = isSearchBarActive;
}
#Override
public void onBackStackChanged() {
for (int i = 0; i < getSupportFragmentManager().getBackStackEntryCount(); i++) {
final BackStackEntry bse = getSupportFragmentManager().getBackStackEntryAt(i);
Log.d("BackStack", "Changed: " + bse.getName());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_LIST) {
if (resultCode == RESULT_OK) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment because dashboard was never added to backstack
DashboardFragment.getInstance().onUpdate();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).onUpdate();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).onUpdate(data);
}
}
}
}
#Override
public void refreshScreen() {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment
DashboardFragment.getInstance().refreshScreen();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).refreshScreen();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).refreshScreen();
} else if (fragment instanceof MarketsFragment) {
((MarketsFragment) fragment).refreshScreen();
}else if (fragment instanceof AlertsContainerFragment) {
((AlertsContainerFragment) fragment).refreshScreen();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
dlDrawer.getDrawerToggle().onConfigurationChanged(newConfig);
}
}
This is a good article to follow for adding a navigation drawer: http://developer.android.com/training/implementing-navigation/nav-drawer.html
Your navigation drawer is showing a blank panel, because the drawer view in your activity_main.xml is a ListView (which you haven't set any data to).
You want to make this view your fragment.
Your activity_main.xml file should look like. Make sure to replace the class on the fragment tag to the correct class of your navigation fragment.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<!-- This fragment container is your the place to put your activities content -->
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/altercolor2" />
<!--
This is your navigation drawer. You can adjust the width here, but it should
be between 240dp and 320dp
-->
<fragment
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
class="com.yourapp.NavigationPanelFragment" />
</android.support.v4.widget.DrawerLayout>
Your MainActivity should look something like this:
public class MainActivity extends AbsBaseaActivity implements OnBackStackChangedListener {
public static final int REQUEST_CODE_LIST = 100;
private Fragment mDrawer;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
public boolean isNavigationOpen() {
return mDrawerLayout.isDrawerOpen(mDrawer);
}
#SuppressWarnings("deprecation")
public void setNavigationOpen(final boolean isNavigationOpen) {
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
if(isNavigationOpen) {
mainButton.setBackgroundResource(R.drawable.bg_helios_active);
} else {
mainButton.setBackgroundDrawable(null);
}
}
public static void newInstance(final Activity activity) {
final Intent intent = new Intent(activity, MainActivity.class);
activity.startActivity(intent);
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
initiateMainActionBar();
final FragmentManager supportFragmentManager = getSupportFragmentManager();
supportFragmentManager.addOnBackStackChangedListener(this);
if (savedInstanceState == null) {
mActiveFragment = DashboardFragment.getInstanceWithTransition(supportFragmentManager);
BangoHelper.onStartSession(this);
} else {
resetToDashboard(supportFragmentManager);
}
//setup drawer
//this is our drawer layout that contains the navigation drawer and your content
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//this is the navigation drawer fragment
mDrawer = (NavigationPanelFragment) findViewById(R.id.drawer);
}
private void resetToDashboard(final FragmentManager supportFragmentManager) {
FragmentStackManager.getInstance().clearBackStack(supportFragmentManager);
mActiveFragment = DashboardFragment.getInstanceWithNoTransition(supportFragmentManager);
}
private void initiateMainActionBar() {
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(R.layout.actionbar_main);
setupOnClickListenerForSearchButton(this);
setupOnClickListenerForMainButton();
setupOnClickListenerForSearchCancelButton(this);
setupOnClickListenerForSearchClearButton(this);
}
private void setupOnClickListenerForSearchCancelButton(final MainActivity activity) {
final Button cancelButton = (Button) findViewById(R.id.button_search_cancel);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
final View actionBarView = findViewById(R.id.action_bar_container);
mIsSearchBarActive = MenuUtils.changeActionBar(activity, actionBarView);
}
});
}
private void setupOnClickListenerForMainButton() {
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
mainButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
toggleNavigationPanel();
}
});
}
#Override
public void manageActionBar() {
setTitle(null);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggleNavigationPanel();
break;
default:
break;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected void onResume() {
final IntentFilter filter = new IntentFilter();
filter.addAction(BroadcastActions.USER_PROFILE);
filter.addAction(BroadcastActions.NEWS_IMAGE);
filter.addAction(BroadcastActions.NEWS_HEADLINES);
registerReceiver(mMainActivityReceiver, filter);
BangoAgent.onResume();
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(mMainActivityReceiver);
super.onPause();
saveTextSize();
}
private void saveTextSize() {
final ContentResolver resolver = EikonApplication.getAppContext().getContentResolver();
final ContentValues contentValues = new ContentValues();
contentValues.put(GenericColumns.TEXT_SIZE, SharedPreferencesManager.getInstance().getTextSize().ordinal());
SqlArguments argument = SqlArgumentsFactory.generateUserProfileUpdateSqlArguments();
String where = argument.getWhereClause();
String[] whereArgs = argument.getWhereArgs();
resolver.update(UserProfileContentProvider.USER_PROFILE_URI, contentValues, where, whereArgs);
}
public void pushNewsArticlePagerFragment(final int position, final String selectedCategoryCode, final boolean isMyNews) {
NewsArticlePagerFragment.newInstance(getSupportFragmentManager(), position, selectedCategoryCode, isMyNews);
}
public void onDashboardClicked(final View view) {
toggleNavigationPanel();
if (isFragmentVisible(DashboardFragment.TAG_DASHBOARD_FRAGMENT)) {
return;
}
final FragmentManager manager = getSupportFragmentManager();
final FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = DashboardFragment.getInstance();
transaction.hide(mActiveFragment);
transaction.show(mActiveFragment);
transaction.commitAllowingStateLoss();
updateActionBarTitle();
}
public void onNewsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(NewsFragment.TAG_NEWS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = NewsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onMarketClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(MarketsFragment.TAG_MARKETS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = MarketsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onListsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(ListsContainerFragment.TAG_LIST_CONTAINER_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = ListsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onBriefcaseClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(BriefcaseFragment.TAG_BRIEFCASE_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = BriefcaseFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onAlertsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(AlertsContainerFragment.TAG_ALERTS_CONTAINER_FRAGMENT)){
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = AlertsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
private void toggleNavigationPanel() {
if (mDrawerLayout.isDrawerOpen(mDrawer))
mDrawerLayout.closeDrawer(mDrawer);
else mDrawerLayout.openDrawer(mDrawer);
final FragmentStackManager manager = FragmentStackManager.getInstance();
setNavigationOpen(setNavigationOpen());
}
public void updateActionBarTitle() {
final String title = FragmentStackManager.getInstance().getTopTitle();
final TextView titleView = (TextView) findViewById(R.id.main_title);
titleView.setText(title);
}
private boolean isFragmentVisible(final String tag) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
return fragment != null && tag.equals(fragment.getTag());
}
public interface BackPressListener<T extends Fragment> {
public boolean backPressed(MainActivity fragmentActivity);
}
private BackPressListener<Fragment> backPressListener = null;
public void setBackPressListener (final BackPressListener<Fragment> backPressListener) {
this.backPressListener = backPressListener;
}
#Override
public void onBackPressed() {
BangoHelper.eventBack();
if (backPressListener != null) {
boolean b = false;
// Making sure we trigger the backPressed event if the listener is the top fragment
String bplTag = ((Fragment)backPressListener).getTag();
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
String topFragemtnTag = "";
if (topFragment != null) {
topFragemtnTag = topFragment.getTag();
if (bplTag != null && topFragemtnTag != null && bplTag.equals(topFragemtnTag)) {
b = backPressListener.backPressed(this);
}
}
if (b) {
return;
}
}
if (mIsSearchBarActive) {
MenuUtils.hideSearchView(this);
mIsSearchBarActive = false;
} else if (mIsNavigationOpen) {
toggleNavigationPanel();
} else if (!FragmentStackManager.getInstance().popTopFragment()) {
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
} else {
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
if (topFragment == null) {
mActiveFragment = DashboardFragment.getInstance();
((DashboardFragment)mActiveFragment).refreshDashboard();
} else if (topFragment instanceof AbsArticlePagerFragment) {
((AbsArticlePagerFragment) topFragment).forceUpdateTextSize();
} else if (topFragment instanceof AbsBaseArticleFragment) {
((AbsBaseArticleFragment) topFragment).forceUpdateTextSize();
}
}
updateActionBarTitle();
}
public void setActiveFragment(final Fragment fragment) {
mActiveFragment = fragment;
}
public void setIsSearchBarActive(final boolean isSearchBarActive){
mIsSearchBarActive = isSearchBarActive;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_LIST) {
if (resultCode == RESULT_OK) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment because dashboard was never added to backstack
DashboardFragment.getInstance().onUpdate();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).onUpdate();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).onUpdate(data);
}else if (fragment instanceof AlertsContainerFragment) {
((AlertsContainerFragment) fragment).onUpdate();
}
}
}
}
#Override
public void refreshScreen() {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment
DashboardFragment.getInstance().refreshScreen();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).refreshScreen();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).refreshScreen();
} else if (fragment instanceof MarketsFragment) {
((MarketsFragment) fragment).refreshScreen();
}
}
#Override
public void retryLoginDelayedData(){
LoginFragment f = new LoginFragment();
f.login("delayed");
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
FragmentStackManager stackManager = FragmentStackManager.getInstance();
Fragment topFragment = stackManager.getTopFragment();
if(topFragment != null){
if(topFragment instanceof ChartFragment){
ChartFragment.replaceInstance(((ChartFragment)topFragment), getSupportFragmentManager(), R.id.fragment_container);
}
}
}
}
Notice that the state of the navigation drawer is managed by the drawer layout. The DrawerLayout and the drawer fragment is bound up in the onCreate method.
Refer to the article i mentioned if you run into trouble.
--- EDIT ----
Below is an activity I have used in an app. It shows how to add the drawer toggle (the link I posted also shows this).
You should be able to merge this with your current activity and have a working navigation drawer.
public class SampleActivity extends AbsBaseaActivity {
private Fragment mDrawer;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerMenuItems = getResources().getStringArray(R.array.home_menu_drawer_titles);
mDrawer = (fragment) findViewById(R.id.drawer);
/* Set up the drawer toggle */
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_closed) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
getActionBar().setTitle(R.string.activity_title);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
/**
* Backward-compatible version of {#link ActionBar#getThemedContext()} that
* simply returns the {#link android.app.Activity} if <code>getThemedContext</code> is unavailable.
*/
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private Context getActionBarThemedContextCompat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return getActionBar().getThemedContext();
} else {
return this;
}
}
#Override protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
mDrawer.setItemChecked(0, true);
}
#Override public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawer)) {
mDrawerLayout.closeDrawer(mDrawer);
} else {
mDrawerLayout.openDrawer(mDrawer);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you are having errors, then post what the errors are.
U can get source ode for navigation drawer from the link below
http://hmkcode.com/android-creating-a-navigation-drawer/
copy this to workspace, or open as a new android project from existing source code.
right click on project > properties >java buildpath> add external jar> choose latest V13 support library from android sdks installed and in order and export tick the jar v13
again right click on project > properties >android>choose abs library. [google for library]
U will get error free working project
All the answer above are awesome but I found it little bit difficult to add it in my existing code so I have created a new class which uses animation and LayoutInflater to add view and removes the navigation drawer to the activity you can use it in fragment also.
NavigationDrawer.java
import android.app.Activity;
import android.support.constraint.ConstraintLayout;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import static android.content.Context.LAYOUT_INFLATER_SERVICE;
public class NavigationDrawer {
//State is the visible state
private Boolean state = false, Transition = false;
private ConstraintLayout mainView;
private ConstraintLayout navigationLayout;
private Animation show, hide;
public NavigationDrawer(Activity activity, ConstraintLayout view) {
this.mainView = view;
LayoutInflater layoutInflater = (LayoutInflater)
activity.getSystemService(LAYOUT_INFLATER_SERVICE);
navigationLayout = (ConstraintLayout) layoutInflater.inflate(R.layout.nav_drawer,
mainView, false);
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
//Show animation
show = new TranslateAnimation(-displayMetrics.widthPixels, 0, 0, 0);
show.setDuration(500);
show.getFillAfter();
show.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
Transition = true;
}
#Override
public void onAnimationEnd(Animation animation) {
Transition = false;
state = true;
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
//Hide animation
hide = new TranslateAnimation(0, -displayMetrics.widthPixels, 0, 0);
hide.setDuration(500);
hide.getFillAfter();
hide.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
Transition = true;
}
#Override
public void onAnimationEnd(Animation animation) {
Transition = false;
state = false;
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
public void toggle() {
if (!Transition) {
if (!state) {
mainView.addView(navigationLayout);
navigationLayout.startAnimation(show);
} else {
navigationLayout.startAnimation(hide);
mainView.removeView(navigationLayout);
}
}
}
}
To use this class.
NavigationDrawer navigationDrawer = new
NavigationDrawer(this,user_activity_main_layout);
//To toggle it
navigationDrawer.toggle();
Here user_activity_main_layout is the Id of root ConstrainLayout you can choose whatever you want.
This works perfect.

Not able to change the Up caret next to the app icon in the ActionBar in my Navigation Drawer

I am currently trying to implement the new NavigationDrawer as per the Google IO 2013 guidelines. I am using ActionbarSherlock. The code is working well. The only issue is that I am not able to toggle the "up" caret next to my app icon when the navigation drawer is pulled out. I am pasting my entire code below. Kindly help.
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
new Thread(new Runnable() {
#Override
public void run() {
prefs = getPreferences(MODE_PRIVATE);
opened = prefs.getBoolean(OPENED_KEY, false);
if(opened == false)
{
mDrawerLayout.openDrawer(mDrawerList);
}
}
}).start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(getMenuItem(item))) {
return true;
}
switch (item.getItemId()) {
case R.id.action_websearch:
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getSupportActionBar().getTitle());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private android.view.MenuItem getMenuItem(final MenuItem item) {
return new android.view.MenuItem() {
#Override
public int getItemId() {
return item.getItemId();
}
public boolean isEnabled() {
return true;
}
#Override
public boolean collapseActionView() {
return false;
}
#Override
public boolean expandActionView() {
return false;
}
#Override
public ActionProvider getActionProvider() {
return null;
}
#Override
public View getActionView() {
return null;
}
#Override
public char getAlphabeticShortcut() {
return 0;
}
#Override
public int getGroupId() {
return 0;
}
#Override
public Drawable getIcon() {
return null;
}
#Override
public Intent getIntent() {
return null;
}
#Override
public ContextMenuInfo getMenuInfo() {
return null;
}
#Override
public char getNumericShortcut() {
return 0;
}
#Override
public int getOrder() {
return 0;
}
#Override
public SubMenu getSubMenu() {
return null;
}
#Override
public CharSequence getTitle() {
return null;
}
#Override
public CharSequence getTitleCondensed() {
return null;
}
#Override
public boolean hasSubMenu() {
return false;
}
#Override
public boolean isActionViewExpanded() {
return false;
}
#Override
public boolean isCheckable() {
return false;
}
#Override
public boolean isChecked() {
return false;
}
#Override
public boolean isVisible() {
return false;
}
#Override
public android.view.MenuItem setActionProvider(ActionProvider actionProvider) {
return null;
}
#Override
public android.view.MenuItem setActionView(View view) {
return null;
}
#Override
public android.view.MenuItem setActionView(int resId) {
return null;
}
#Override
public android.view.MenuItem setAlphabeticShortcut(char alphaChar) {
return null;
}
#Override
public android.view.MenuItem setCheckable(boolean checkable) {
return null;
}
#Override
public android.view.MenuItem setChecked(boolean checked) {
return null;
}
#Override
public android.view.MenuItem setEnabled(boolean enabled) {
return null;
}
#Override
public android.view.MenuItem setIcon(Drawable icon) {
return null;
}
#Override
public android.view.MenuItem setIcon(int iconRes) {
return null;
}
#Override
public android.view.MenuItem setIntent(Intent intent) {
return null;
}
#Override
public android.view.MenuItem setNumericShortcut(char numericChar) {
return null;
}
#Override
public android.view.MenuItem setOnActionExpandListener(OnActionExpandListener listener) {
return null;
}
#Override
public android.view.MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) {
return null;
}
#Override
public android.view.MenuItem setShortcut(char numericChar, char alphaChar) {
return null;
}
#Override
public void setShowAsAction(int actionEnum) {
}
#Override
public android.view.MenuItem setShowAsActionFlags(int actionEnum) {
return null;
}
#Override
public android.view.MenuItem setTitle(CharSequence title) {
return null;
}
#Override
public android.view.MenuItem setTitle(int title) {
return null;
}
#Override
public android.view.MenuItem setTitleCondensed(CharSequence title) {
return null;
}
#Override
public android.view.MenuItem setVisible(boolean visible) {
return null;
}
};
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends SherlockFragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
// change int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()), "drawable", getActivity().getPackageName());
int imageId = getResources().getIdentifier("tempmap", "drawable", getActivity().getPackageName());
// change ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
// change getActivity().setTitle(planet);
getActivity().setTitle("MapView");
return rootView;
}
}
}
If you don't need the 3 lines to move (like in gmail app), you could just add:
<item name="homeAsUpIndicator">#drawable/ic_drawer</item>
<item name="android:homeAsUpIndicator">#drawable/ic_drawer</item>
in your activity's theme. I prefer this to using yet another library in my app.
ic_drawer can be downloaded from here:
http://developer.android.com/training/implementing-navigation/nav-drawer.html
try to call syncState on the toggle drawer like this:
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
//your ActionBarDrawerToggle is below
mDrawerToggle.syncState();
}
or just right after you instantiate it.
I had the same problem and did some research on that topic. It does not seem to be easy to get the caret working correctly on older SDKs. Long story short, there's a guy who has a running example implementation that's based on reflection:
https://github.com/nicolasjafelle/SherlockNavigationDrawer
I tested it and it works perfectly for me, even on Android 2.x !
I have the caret removed in 4.x devices, but not for 2.x devices. The repository is here if you need it:
https://github.com/bcrider/NavigationDrawerSherlocked
It's simply the sample that Google supplied that I modified using ActionBarSherlock as you have done as well. I fixed an issue with a method (onOptionsItemSelected) in the sample that originally prevented the tapped icon from doing anything after ActionBarSherlock was integrated into the app.
Hope this helps!

Categories

Resources