Android DrawerLayout - too slow upon item click - android

I want my navigation drawer to open the fragment smoothly upon click and close itself without any lag.
Here is the code -
#Override
protected void onCreate(Bundle savedInstanceState) {
navigationView.setNavigationItemSelectedListener(this);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
// Set the drawer toggle as the DrawerListener
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
}
onNavigationItemSelected(navigationView.getMenu().getItem(0));
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
/* clear backstack of all elements but the last one
* which is the car keys screen
*/
for (int i = 1; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
}
navigationView.getMenu().findItem(R.id.navigation_settings).setVisible(false);
switch (menuItem.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
}
if (menuItem.getGroupId() == R.id.group_top) {
navigationView.getMenu().setGroupCheckable(R.id.group_bottom, false, true);
navigationView.getMenu().setGroupCheckable(R.id.group_top, true, true);
} else {
navigationView.getMenu().setGroupCheckable(R.id.group_bottom, true, true);
navigationView.getMenu().setGroupCheckable(R.id.group_top, false, true);
}
//Update highlighted item in the navigation menu
menuItem.setChecked(true);
if (fragment != null) {
drawerLayout.closeDrawer(navigationView);
setTitle(menuItem.getTitle());
menuItem.setChecked(true);
fm.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack("fragment")
.commit();
return true;
}
return false;
}
This is in the MainActivity.
Where am I going wrong? Why does it not run smoothly?
Thank you in advance :)

try putting it in a thread with a little delay so it will finish his other commands , like :
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(drawerLayout!=null)
drawerLayout.closeDrawer(navigationView);
}
}, 150);

Related

Navigation Drawer Back Stack doesn't work

I have an app developed like the following image:
So a fragment A with a menu. Clicking on the menu it will open a fragment B.
My problem is that, when I click on the back button, nothing happens, so I can not return from fragment B to fragment A, and I don't understand why.
This is my code:
Main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final DrawerLayout drawer = findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
drawer.openDrawer(Gravity.LEFT);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentA fragmentA = new FragmentA();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.relativelayout_for_fragment, fragmentA, fragmentA.getTag()).commit();
getSupportActionBar().setTitle(getResources().getString(R.string.title));
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() == 0){
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
toggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
}else{
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
toggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
drawer.openDrawer(GravityCompat.START);
} else {
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
Fragment A (on click on the menu)
Fragment fragmentB = new FragmentB();
FragmentTransaction transaction = activity.getFragmentManager().beginTransaction();
transaction.replace(R.id.relativelayout_for_fragment, fragmentB);
transaction.addToBackStack(null);
transaction.commit();
Fragment B
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.share_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getFragmentManager().popBackStack();
return true;
case R.id.menu_item_share:
String contenuto = "*" + titolo + "*" + "\n" + desc;
String textToShare = getResources().getString(R.string.Linc);
Intent intent = new Intent("android.intent.action.SEND");
intent.setType("text/plain");
intent.putExtra("android.intent.extra.TEXT", contenuto + "\n\n" + textToShare);
startActivity(Intent.createChooser(intent,
getResources().getString(R.string.sharing)));
return true;
}
return super.onOptionsItemSelected(item);
}
did you try this onBackPressed
override fun onBackPressed() {
val manager: FragmentManager = supportFragmentManager
if(manager.backStackEntryCount > 0){
manager.popBackStack()
}else{
super.onBackPressed()
}
}
In MainActivity
After
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Put
getSupportFragmentManager().popBackStack()

Navigation Drawer Backstacks with Fragments

My app uses a navigation drawer with 2 sections.
Section 1: Character List, Favorites List
Section 2: List of all characters
Character List has the same character selections as section 2 in the navigation drawer. Selecting a character from "Character List" or "Favorites List" in section 1, or from the list in the drawer, will open the character page.
When I am on a character page, I want the back button to bring the user back to the Character List or Favorites List (whichever was last accessed), but never back to a previous Character Page (if it was selected from the navigation drawer).
My Drawer item listener:
public void getDrawerItemClickListener() {
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
int selection = menuItem.getItemId();
String name = menuItem.getTitle().toString();
if(selection == R.id.nav_home) {
Fragment myFragment = new HomeFragment();
replaceFragment(myFragment);
}
if(selection == R.id.nav_fav) {
Fragment myFragment = new FavFragment();
replaceFragment(myFragment);
}
for(int i = 0; i < characters.size(); i++) {
if(characters.get(i).getName().equals(name))
{
Fragment myFragment = new TabFragment();
myFragment.setArguments(createCharacterBundle(characters.get(i)));
replaceFragment(myFragment);
break;
}
}
return false;
}
});
}
My replaceFragment method:
public void replaceFragment(Fragment myFragment) {
FragmentTransaction transaction = mFragmentManager.beginTransaction();
transaction.replace(R.id.containerView, myFragment);
transaction.commit();
}
And my onBackPressed method:
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(View drawerView) {
mDrawerOpen = true;
}
#Override
public void onDrawerClosed(View drawerView) {
mDrawerOpen = false;
}
#Override
public void onDrawerStateChanged(int newState) {
}
});
public void onBackPressed() {
if (mDrawerOpen) {
mDrawerLayout.closeDrawer(DrawableItemResourceID);
return;
} else {
super.onBackPressed();
}
}

Why not works ClickListeners for Toolbar?

I use MaterialDrawer and code MainActivity is:
public class MainActivity extends AppCompatActivity implements KitchenFragment.CallbackOne {
public static final String TAG = "myLogTag";
private Toolbar mToolbar;
private Drawer drawer;
private FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "CLICK NOCL");
}
});
setSupportActionBar(mToolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(false);
fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.content_frame);
if (fragment == null) {
fragment = MenuFragment.newInstance();
fm.beginTransaction()
.add(R.id.content_frame, fragment)
.commit();
}
drawer = new DrawerBuilder()
.withActivity(this)
.withToolbar(mToolbar)
.withActionBarDrawerToggle(true)
.withHeader(R.layout.drawer_header)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.menu).withIdentifier(1),
new PrimaryDrawerItem().withName(R.string.kitchen_title).withIdentifier(2),
new PrimaryDrawerItem().withName(R.string.information_title).withEnabled(false)
).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
Log.d(TAG, "position clicked: " + position);
Fragment fragment = MenuFragment.newInstance();
switch (position) {
case 1:
fragment = MenuFragment.newInstance();
break;
case 2:
fragment = KitchenFragment.newInstance();
break;
default:
fragment = new Fragment();
}
fm.beginTransaction().replace(R.id.content_frame, fragment).commit();
return false;
}
})
.withFireOnInitialOnClick(true)
.withSavedInstance(savedInstanceState)
.withOnDrawerNavigationListener(new Drawer.OnDrawerNavigationListener() {
#Override
public boolean onNavigationClickListener(View view) {
Log.d(TAG, "CLICK in DNL");
if (!drawer.getActionBarDrawerToggle().isDrawerIndicatorEnabled()) {
onBackPressed();
return true;
} else
return false;
}
})
.build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "CLICK OIS");
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case android.R.id.home:
getFragmentManager().popBackStackImmediate();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState = drawer.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen())
drawer.closeDrawer();
else if (getFragmentManager().getBackStackEntryCount() == 1) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawer.getActionBarDrawerToggle().syncState();
getFragmentManager().popBackStack();
} else if (getFragmentManager().getBackStackEntryCount() > 0)
getFragmentManager().popBackStack();
else
super.onBackPressed();
}
#Override
public void setFirstSelected() {
drawer.setSelection(1);
}
}
I'm trying to trace a Click in mToolbar.setNavigationOnClickListener
and withOnDrawerNavigationListener and onOptionsItemSelected.
None of the listeners not reacted for clicking.
How you see i use Activity that launches Fragment (1), which in turn lets Fragment (2 and 3). In 2 and 3 Fragment in OnCreate i use ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); , and I need to by pressing the back button (in toolbar), returning the previous fragment, and not open Drawer
The MaterialDrawer already handles all the listeners for you. If you need to do an action after the drawer opens or closes you can provide the listener via the DrawerBuilder
For the icon you have this listener:
OnDrawerNavigationListener
https://github.com/mikepenz/MaterialDrawer/blob/develop/library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java#L1158
For drawer close / open this listener:
OnDrawerListener
https://github.com/mikepenz/MaterialDrawer/blob/develop/library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java#L1116
I suggest you to create new Activity using android studio wizard. File->New->Activity->Navigation Drawer Activity.
In that case ActionBarDrawerToaggle is used
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
This toggle contains click listener which handle open/close drawer functionality for you.
Also you can that item clicks implemented through OnNavigationItemSelectedListener.onNavigationItemSelected(MenuItem item)

Toolbar hamburger on click listener?

I'm implementing persistent search view like google play in my android application.here is my code.
public class NavigationDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private EditText searchView;
private ActionBarDrawerToggle toggle;
private DrawerLayout drawer;
private TextView appName;
private boolean isNavigationDrawerOpened;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
CoordinatorLayout coordinatorLayout = (CoordinatorLayout)findViewById(R.id.mainLayout);
coordinatorLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(isNavigationDrawerOpened){
hideSearchAndEnableAppName();
}
return false;
}
});
searchView = (EditText) findViewById(R.id.searchView);
appName = (TextView) findViewById(R.id.appName);
searchView.setVisibility(View.GONE);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(),"asdfasdfasdf",Toast.LENGTH_LONG).show();
return false;
}
});
drawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "asdfasfasdf", Toast.LENGTH_SHORT).show();
}
});
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(NavigationDrawerActivity.this,"yayyy mani got it",Toast.LENGTH_LONG).show();
}
});
appName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isNavigationDrawerOpened) {
searchView.setVisibility(View.VISIBLE);
searchView.requestFocus();
appName.setVisibility(View.GONE);
isNavigationDrawerOpened = true;
animateDrawerIndicator(true);
InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(view.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
}
}
});
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void hideSearchAndEnableAppName() {
animateDrawerIndicator(false);
isNavigationDrawerOpened = false;
searchView.setVisibility(View.GONE);
appName.setVisibility(View.VISIBLE);
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else if(isNavigationDrawerOpened){
hideSearchAndEnableAppName();
}else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
drawer.openDrawer(GravityCompat.START);
Toast.makeText(getApplicationContext(),"asdfasdf",Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void animateDrawerIndicator(boolean shouldAnimate) {
ValueAnimator anim;
if(shouldAnimate) {
anim = ValueAnimator.ofFloat(0, 1);
} else {
anim = ValueAnimator.ofFloat(1, 0);
}
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float slideOffset = (Float) valueAnimator.getAnimatedValue();
// You should get the drawer layout and
// toggler from your fragment to make the animation
toggle
.onDrawerSlide(drawer,
slideOffset);
}
});
anim.setInterpolator(new DecelerateInterpolator());
anim.setDuration(500);
anim.start();
}
}
Here everything is working fine, but when user has clicked on toolbar edittext(as per my code) i'm changing the hamburger icon to back button. Now if user clicks on back button, it should animate back to hamburger and edittext should be hidden(as per my requirement)
But, for that to happen i need to handle hamburger click. I have tried onClickListners on toggle,actionbartoggle etc.But in vain please help.
When both toolbar and drawer were present.
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerToggle.setDrawerIndicatorEnabled(false); //disable "hamburger to arrow" drawable
mDrawerToggle.setHomeAsUpIndicator(R.drawable.menu); //set your own
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mDrawerLayout.isDrawerOpen(GravityCompat.START)){
mDrawerLayout.closeDrawer(GravityCompat.START);
}else {
mDrawerLayout.openDrawer(GravityCompat.START);
}
}
});
This is I used in my app when Change the hamburger icon with other
when set icon than on click of that is not working because
we need to use:
mDrawerToggle.setDrawerIndicatorEnabled(false);
But when only toolbar(No Navigation Drawer):
toolbar = (Toolbar) findViewById(R.id.toolbar);
toggle = new ActionBarDrawerToggle(
this, null, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerToggle.setDrawerIndicatorEnabled(false); //disable "hamburger to arrow" drawable
mDrawerToggle.setHomeAsUpIndicator(R.drawable.menu); //set your own
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mDrawerLayout.isDrawerOpen(GravityCompat.START)){
mDrawerLayout.closeDrawer(GravityCompat.START);
}else {
mDrawerLayout.openDrawer(GravityCompat.START);
}
}
});
Then change the hamburger icon to any other as:
toolbar.setNavigationIcon(R.drawable.ic_dehaze_black_24dp);
Directly calling an ActionBarDrawerToggle's onDrawerSlide() method to animate the toggle is messy. A better option is to set a DrawerArrowDrawable as the toggle's Up indicator, and animate that ourselves instead, enabling and disabling the toggle's drawer indicator as necessary.
First, we declare a DrawerArrowDrawable field in the Activity.
private DrawerArrowDrawable searchToggle;
We then initialize it in the onCreate() method, set it as the Up indicator, and define the navigation OnClickListener.
searchToggle = new DrawerArrowDrawable(this);
toggle.setHomeAsUpIndicator(searchToggle);
toggle.setToolbarNavigationClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
hideSearchAndEnableAppName();
}
}
);
In the animateDrawerIndicator() method, we first disable the drawer indicator if we're showing the search EditText. This causes the toggle to revert to the Up indicator, which we'll then animate as necessary, switching back to the drawer indicator once the hiding animation is finished.
public void animateDrawerIndicator(final boolean shouldAnimate) {
ValueAnimator anim;
if (shouldAnimate) {
anim = ValueAnimator.ofFloat(0, 1);
// Show the Up indicator instead
// of the drawer indicator
toggle.setDrawerIndicatorEnabled(false);
}
else {
anim = ValueAnimator.ofFloat(1, 0);
}
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float slideOffset = (Float) valueAnimator.getAnimatedValue();
// Animate our Drawable instead of the drawer's
searchToggle.setProgress(slideOffset);
// If we're hiding and have finished,
// re-enable the drawer indicator
if(!shouldAnimate && slideOffset == 0) {
toggle.setDrawerIndicatorEnabled(true);
}
}
});
anim.setInterpolator(new DecelerateInterpolator());
anim.setDuration(500);
anim.start();
}

Fragment not showing

So I've been basing my navigation drawer after code i found in a tutorial. However my fragments don't switch. Laptop is down and using AIDE. Anyone tell me what's wrong? Guessing it's my setonitemclicklistener.
{
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems()
{
String[] osArray = { "Hello", "Watch Ads", "TapJoy" };
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
selectView(position);
}
});
}
private void selectView(int position)
{
Fragment fragment = null;
switch (position)
{
case 0:
fragment = new HelloFragment();
break;
case 1 :
fragment = new AdFragment();
break;
case 2:
fragment = new TapJoyFragment();
break;
}
if (fragment == null)
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
} }
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("How will you earn?");
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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
Hello dude !
private void selectView(int position)
{
Fragment fragment = null;
switch (position)
{
case 0:
fragment = new HelloFragment();
break;
case 1 :
fragment = new AdFragment();
break;
case 2:
fragment = new TapJoyFragment();
break;
}
**if (fragment == null)**
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
} }
This "if" statement alway be false How can fragment be null if u wrap it just before in switch(position). Thats why your fragment transaction will never come true.
Firstly take FragmentActivity instead of Activity...
private void selectView(int position)
{
Fragment fragment = null;
switch (position)
{
case 0:
fragment = new HelloFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,fragment).commit();
break;
case 1 :
fragment = new AdFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,fragment).commit();
break;
case 2:
fragment = new TapJoyFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,fragment).commit();
break;
}
Please use if(fragment != null) instead of (fragment == null).

Categories

Resources