I have implemented a drawer layout whereby when I click a navigation view item a tab layout opens up. The tablayout comes in fine but the problem is when i click the back button of the tab layout the application crashes with No drawer view found with gravity LEFT. Also I have noticed that there is a bit of a lag when the navigation drawer closes when the tab layout comes in, the drawer does not close smoothly.
Below is my java code and xml:
public class Navigation extends AppCompatActivity implements
ItemFragment.OnHeadlineSelectedListener,
SortFragment.OnHeadlineSelectedListener{
private static final String TAG = Navigation.class.getSimpleName();
Toolbar toolbar;
FragmentManager mFragmentManager;
private TextView mCounter;
private ImageView cart;
FragmentTransaction mFragmentTransaction;
public int id, tabPosition = 0, tabPositionNavigation = 0;
private String drinkToSort = "empty";
SharedPreferences preferences;
private LocalStore localStore;
private String userName, email, location;
private String phone;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation);
localStore = new LocalStore(this);
id = localStore.getLoggedInUser().getId();
userName = localStore.getLoggedInUser().getUserName();
email = localStore.getLoggedInUser().getEmail();
phone = localStore.getLoggedInUser().getPhone();
Log.i(TAG,"USERDATA" + "[" + id + userName + email + phone + location + "]");
relativeLayout = (RelativeLayout) findViewById(R.id.main_content);
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle("hello");
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle("hello");
}
};
Bundle extras = getIntent().getExtras();
if (extras != null) {
this.tabPosition = extras.getInt("tabPosition");
this.tabPositionNavigation = extras.getInt("tabPositionNavigation");
this.drinkToSort = extras.getString("drinkToSort");
Log.d(TAG, tabPosition + tabPositionNavigation + drinkToSort);
}
Bundle bundle = new Bundle();
bundle.putString("drinkToSort", drinkToSort);
LiquorFragment obj = new LiquorFragment();
obj.setArguments(bundle);
int width = getResources().getDisplayMetrics().widthPixels/2;
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_container, new NavigationFragment()).commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.details_activity, menu);
RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.cart_no).getActionView();
mCounter = (TextView) badgeLayout.findViewById(R.id.counter);
Log.d("sameSelectionCount", CartCounter.getCounter()+"");
mCounter.setText(""+CartCounter.getCounter());
cart = (ImageView) badgeLayout.findViewById(R.id.cart);
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("cart_no","cart_no");
Intent intent = new Intent(getApplicationContext(), ShoppingList.class);
startActivity(intent);
}
});
return true;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onResume() {
super.onResume();
//TabFragment.viewPager.setCurrentItem(1);
Log.d("landposzq",tabPositionNavigation + "");
if (tabPositionNavigation != 0){
if (tabPositionNavigation == 1){
NavigationFragment.viewPager.setCurrentItem(0);
} else if (tabPositionNavigation == 2){
NavigationFragment.viewPager.setCurrentItem(1);
} else if (tabPositionNavigation == 3){
NavigationFragment.viewPager.setCurrentItem(2);
} else if (tabPositionNavigation == 4){
NavigationFragment.viewPager.setCurrentItem(3);
} else if (tabPositionNavigation == 5){
NavigationFragment.viewPager.setCurrentItem(4);
}
}
}
}
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:openDrawer="start"
android:fitsSystemWindows="true">
<!--Main content-->
<RelativeLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/qb"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar" />
</RelativeLayout>
<!--Navigation Drawer-->
<android.support.design.widget.NavigationView
android:id="#+id/main_drawer"
android:layout_width="290dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="#color/white"
app:headerLayout="#layout/drawer_header"
app:itemTextColor="#000000"
app:itemIconTint="#color/qb"
app:menu="#menu/menu_drawer" >
<LinearLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginLeft="20dp"
android:src="#drawable/balloon4"
/>
<TextView
android:id="#+id/free_drinks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffff99"
android:gravity="center_vertical"
android:padding="10dp"
android:drawableRight="#drawable/direction"
android:height="60dp"
android:textSize="18sp"
android:text="GET FREE DRINKS"
android:textColor="#000000"
android:layout_gravity="bottom"
/>
</LinearLayout>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Change your onBackPressed() method as below :
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
Related
In MainActivity, I've created a DrawerLayout and ActionBar. Is there any way to use that same Drawer and ActionBar in other activities without writing the same code again? Here's the code I'm using:
Main.xml:
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:titleTextColor="#FFF"></androidx.appcompat.widget.Toolbar>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorPrimary"
>
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/homepage_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
></androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/main_nav"
android:layout_width="277dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer_menu"></com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
Main Java (I've Removed The Extra Code [Non Drawer-Actionbar Code]):
DrawerLayout drawerLayout;
Toolbar toolbar;
TextView json;
RequestQueue requestQueue;
ActionBarDrawerToggle actionBarDrawerToggle;
private RequestQueue mqueue;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mqueue = Volley.newRequestQueue(this);
setuptools();
setUpToolbar();
}
private void setUpToolbar()
{
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.app_name,R.string.app_name) ;
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
toolbar.setNavigationIcon(R.drawable.ic_menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.right_menu,menu);
final MenuItem awesomeMenuItem = menu.findItem(R.id.notification_iconmain);
View awesomeActionView = awesomeMenuItem.getActionView();
awesomeActionView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(awesomeMenuItem);
}
});
final TextView not_num = (TextView) menu.findItem(R.id.notification_iconmain).getActionView().findViewById(R.id.hotlist_hot);
String username = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
String server_url = "https://google.com/api/notifications.php?username="+username;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, server_url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject notification_numbers = jsonArray.getJSONObject(i);
String final_num = notification_numbers.getString("notifications");
if(final_num.equals("0")){
}else{
not_num.setVisibility(View.VISIBLE);
not_num.setText(final_num);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
mqueue.add(request);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.notification_iconmain){
Intent intent_noti = new Intent(this, NotificationsPage.class);
this.startActivity(intent_noti);
}
if(id == R.id.user_icon){
Intent intent_user = new Intent(this, Profile_Page.class);
this.startActivity(intent_user);
}
return super.onOptionsItemSelected(item);
}
}
What It Does:
It creates a slider drawer, an action bar with the right side menu, and displays the notification count on Bell Icon, and each item has its custom on-click event.
Now, how I can use the same drawer, action bar without writing the code again and again in each activity.
Menu Item click not working I tried various things but it won't work.
Here are my code:
Home Activity:
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private Button mBtRequest;
private Button mBtContinue;
private ProfileFragment mProfileFragment;
private SetPreferences Setpref;
private SlideUp slideUp;
private View dim;
private View sliderView;
Toast toast;
private TextView mTvDrawerName;
private TextView mTvDrawerMobile;
private TextView mtoolbarTitle;
private String mfullName;
private String mMobile;
private SharedPreferences mSharedPreferences;
private CompositeSubscription mSubscriptions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
Setpref = new SetPreferences(this);
if (!Setpref.IsLoggined()) {
gotoMain();
finish();
}
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
mSubscriptions = new CompositeSubscription();
initSharedPreferences();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.findViewById(R.id.toolbar_title).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(v, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mBtRequest = (Button) findViewById(R.id.btn_request);
mBtContinue = (Button) findViewById(R.id.btn_continue);
mBtRequest.setOnClickListener(view -> slideUp());
mBtContinue.setOnClickListener(view -> checkout());
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
sliderView = findViewById(R.id.slideView);
sliderView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (toast != null){
toast.cancel();
}
toast = Toast.makeText(HomeActivity.this, "click", Toast.LENGTH_SHORT);
toast.show();
}
});
dim = findViewById(R.id.dim);
slideUp = new SlideUpBuilder(sliderView)
.withListeners(new SlideUp.Listener.Events() {
#Override
public void onSlide(float percent) {
dim.setAlpha(1 - (percent / 100));
}
#Override
public void onVisibilityChanged(int visibility) {
if (visibility == View.GONE){
// fab.show();
}
}
})
.withStartGravity(Gravity.BOTTOM)
.withLoggingEnabled(true)
.withGesturesEnabled(true)
.withStartState(SlideUp.State.HIDDEN)
.build();
Typeface myraid_bold = Typeface.createFromAsset(getAssets(),"fonts/MyriadPro-Bold_0.otf");
Typeface myraid_semibold = Typeface.createFromAsset(getAssets(),"fonts/MyriadPro-Semibold_0.otf");
View header = navigationView.getHeaderView(0);
mTvDrawerName = (TextView) header.findViewById(R.id.nav_user_name);
mTvDrawerMobile = (TextView) header.findViewById(R.id.nav_mobile_number);
mtoolbarTitle = (TextView) findViewById(R.id.toolbar_title);
mTvDrawerName.setText(mfullName);
mTvDrawerMobile.setText(mMobile);
mTvDrawerName.setTypeface(myraid_bold);
mTvDrawerMobile.setTypeface(myraid_bold);
mtoolbarTitle.setTypeface(myraid_semibold);
mBtRequest.setTypeface(myraid_bold);
mBtContinue.setTypeface(myraid_bold);
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mfullName = mSharedPreferences.getString(Constants.FULLNAME,"");
mMobile = mSharedPreferences.getString(Constants.MOBILE,"");
}
private void gotoProfile(){
if (mProfileFragment == null) {
mProfileFragment = new ProfileFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragmentFrame,mProfileFragment,ProfileFragment.TAG).commit();
}
private void gotoMain(){
Setpref.setIsLoggined(false);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
private void slideUp(){
slideUp.show();
}
private void checkout(){
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(Constants.MOBILE,"");
editor.putString(Constants.TOKEN,"");
editor.putString(Constants.FULLNAME,"");
editor.apply();
gotoMain();
}
private void showSnackBarMessage(String message) {
Snackbar.make(findViewById(R.id.drawer_layout),message,Snackbar.LENGTH_SHORT).show();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_my_addresses) {
// Handle the camera action
} else if (id == R.id.nav_my_orders) {
} else if (id == R.id.nav_refer) {
} else if (id == R.id.nav_logout) {
logout();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
activity_home_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_my_addresses"
android:icon="#drawable/ic_location_on_white_24px"
android:title="My Addresses" />
<item
android:id="#+id/nav_my_orders"
android:icon="#drawable/ic_history_white_24px"
android:title="My Orders" />
<item
android:id="#+id/nav_refer"
android:icon="#drawable/ic_record_voice_over_white_24px"
android:title="Refer & Earn" />
</group>
<group
android:id="#+id/menu_bottom"
android:checkableBehavior="none">
<item
android:id="#+id/nav_logout"
android:icon="#drawable/ic_exit_to_app_white_24px"
android:title="Logout" />
</group>
</menu>
nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Aashish Kaushik"
android:id="#+id/nav_user_name"
android:textColor="#android:color/white"/>
<TextView
android:id="#+id/nav_mobile_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9910454530"
android:textColor="#android:color/white"/>
</LinearLayout>
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<FrameLayout
android:alpha="0"
android:id="#+id/dim"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/dimBg" />
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_home_drawer" />
<!-- The Fragment -->
<FrameLayout
android:id="#+id/fragmentFrame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.DrawerLayout>
When I try to view activity_home.xml as a design it will not showing left drawer but when I install the app on device it will show the left drawer on click but when I click on any time it will not showing check able box and not working.
Update These lines of code works for me.. after update clean and rebuild Project.
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.bringToFront();
Here is a simple solution to address this issue. You can just link your HomeActivity methods to the menu items (whichever you want to). Now just create your methods and go to the menu layout. In the menu layout just add the android:onClick inside the item tag and put the particular method name inside it. And you are done. Let me know if this was useful.
I followed a tutorial to push facebook info from login into an activity with a navigation, then put the into on top, as shown, which, after days of altering code, I finally got it to work.
But now I cant get the original header to go away. I've tried changing every part of the code, but I always end up with all or nothing. I know two heads are better than one, but this is an exception to the rule.
Also, I guess I cant post images, so, the original header is on top, where it should be.
The new header with my facebook profile picture and info, is underneath that.
And below that, starts the navigation drawer menu.
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
JSONObject response, profile_pic_data, profile_pic_url;
TextView user_name, user_email, tokens;
ImageView user_picture;
NavigationView navigation_view;
String name;
Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
tokens = (TextView)findViewById(R.id.textView17);
button2 = (Button)findViewById(R.id.button2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
String jsondata = intent.getStringExtra("jsondata");
final String uid = intent.getStringExtra("Uid");
setNavigationHeader(); // call setNavigationHeader Method.
setUserProfile(jsondata, uid);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.INVISIBLE);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Firebase ref = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + MainActivity.uID + "/");
Tokens token = new Tokens("100");
ref.setValue(token);
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Toast.makeText(getApplicationContext(), uid, Toast.LENGTH_LONG).show();
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
updateText();
}
});
Firebase ref = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + MainActivity.uID + "/");
Firebase tokRef = ref.child("tokens");
//tokRef.setValue(mAuthData.getProvider());
//Tokens token = new Tokens(100);
//ref.setValue(token);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child("tokens").getValue() != null) {
name = (String) dataSnapshot.child("tokens").getValue().toString();
tokens.setText(name);
//tokens.setText(dataSnapshot.getValue().toString());
// Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
// System.out.println(dataSnapshot.getValue());
// String woot = dataSnapshot.getValue().toString();
// tokens.setText(woot);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getApplicationContext(), "couldnt update token text", Toast.LENGTH_LONG).show();
}
});
}
public void updateText(){
Firebase ref = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + MainActivity.uID + "/");
Firebase tokRef = ref.child("tokens");
//tokRef.setValue(mAuthData.getProvider());
// Tokens token = new Tokens(100);
// ref.setValue(token);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot tokenSnapshot: dataSnapshot.getChildren()){
Tokens token = tokenSnapshot.getValue(Tokens.class);
System.out.println(token.toString());
name = token.toString();
// name = (String) dataSnapshot.child("tokens").getValue();
tokens.setText(name);
}
// name = (String) dataSnapshot.child("tokens").getValue().toString();
// tokens.setText(name);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getApplicationContext(), "couldnt update token text", Toast.LENGTH_LONG).show();
}
});
}
public void setNavigationHeader(){
navigation_view = (NavigationView) findViewById(R.id.nav_view);
navigation_view.removeHeaderView(null);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
navigation_view.addHeaderView(header);
user_name = (TextView) header.findViewById(R.id.username);
user_picture = (ImageView) header.findViewById(R.id.profile_pic);
user_email = (TextView) header.findViewById(R.id.email);
}
public void setUserProfile(String jsondata, String uid){
try
{
response = new JSONObject(jsondata);
user_email.setText(response.get("email").toString());
// user_email.setText(MainActivity.uEmail);
user_name.setText(response.get("name").toString());
// user_name.setText(MainActivity.uName);
profile_pic_data = new JSONObject(response.get("picture").toString());
profile_pic_url = new JSONObject(profile_pic_data.getString("data"));
Picasso.with(this).load(profile_pic_url.getString("url")).into(user_picture);
}
catch
(Exception e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, 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;
}
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_slots) {
// Handle the camera action1
Intent intent2 = new Intent(this, SlotPageView.class);
startActivity(intent2);
} else if (id == R.id.nav_spin) {
Intent intent2 = new Intent(this, DailySpinActivity.class);
startActivity(intent2);
} else if (id == R.id.nav_offers) {
} else if (id == R.id.nav_prizes) {
Intent intent2 = new Intent(this, PrizesActivity.class);
startActivity(intent2);
} else if (id == R.id.nav_winners) {
Intent intent2 = new Intent(this, WinnersActivity.class);
startActivity(intent2);
} else if (id == R.id.nav_stats) {
} else if (id == R.id.nav_account) {
Intent intent2 = new Intent(this, AccountActivity.class);
startActivity(intent2);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
android:fitsSystemWindows="true" tools:openDrawer="start">
<include layout="#layout/app_bar_home" android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView android:id="#+id/nav_view"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:layout_gravity="start" android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_home" app:menu="#menu/activity_home_drawer" />
App bar home xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context="learn2crack.learn2crackfb.HomeActivity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_home" />
<android.support.design.widget.FloatingActionButton android:id="#+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Nav header home xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark" android:orientation="vertical"
android:gravity="bottom">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_pic"
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:src="#android:drawable/sym_def_app_icon"
/>
<TextView android:id="#+id/username"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textSize="14dp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#000000" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="android.studio#android.com" />
</LinearLayout>
u have to pass the header view into
navigation_view.removeHeaderView(navigation_view.getHeaderView(0);
and not null
navigation_view.removeHeaderView(null);
when you add header using app:headerLayout="#layout/nav_header_home" just like below
<android.support.design.widget.NavigationView android:id="#+id/nav_view"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:layout_gravity="start" android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_home" app:menu="#menu/activity_home_drawer" />
then no need to add header again from code
remove below lines from setNavigationHeader() method
navigation_view.removeHeaderView(null);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
navigation_view.addHeaderView(header);
after remove method look like below
Edit /
public void setNavigationHeader(){
navigation_view = (NavigationView) findViewById(R.id.nav_view);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
user_name = (TextView) navigation_view.findViewById(R.id.username);
user_picture = (ImageView) navigation_view.findViewById(R.id.profile_pic);
user_email = (TextView) navigation_view. findViewById(R.id.email);
}
Try this, It's workable and tested.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.removeHeaderView(navigationView.getHeaderView(0));
View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_main);
ImageView user_dp = headerLayout.findViewById(R.id.user_dp);
TextView user_fullname = headerLayout.findViewById(R.id.user_fullname);
TextView user_email = headerLayout.findViewById(R.id.user_email);
user_dp.setBackgroundResource(R.drawable.user);
user_fullname.setText(fullName);
user_email.setText(uemail);
}
My BaseDrawerActivity extends BaseActivity and I have a Toolbar in BaseActivity.
The toolbar shows with no issues in classes that extend BaseActivity, but ALL classes that extend BaseDrawerActivity just show a blank toolbar. The nav drawer works fine.
When I had one main activity class (BaseActivity + BaseDrawerActivity) the toolbar showed no problem and the nav drawer worked.
Why is my implementation here not showing the Toolbar? I debugged and getToolbar() is returning the toolbar for sure.
activity_base_drawer.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar"/>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foreground="?android:windowContentOverlay">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<include layout="#layout/call_to_action_banner"/>
</FrameLayout>
<ListView
android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
style="#style/NavDrawerListView" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:theme="#style/ToolbarOverlay"
android:popupTheme="#style/ToolbarOverlay"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:minHeight="?attr/actionBarSize"
android:elevation="10dp"/>
BaseDrawerActivity
public abstract class BaseDrawerActivity extends BaseActivity {
private static final int LAYOUT_ID = R.layout.activity_base_drawer;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private NavDrawerAdapter mNavDrawerAdapter;
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)){
mDrawerLayout.closeDrawers();
} else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(LAYOUT_ID);
setupNavDrawer();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
private void setupNavDrawer() {
final ListView navDrawerListView = (ListView) findViewById(R.id.navigation_drawer);
View header = getLayoutInflater().inflate(R.layout.nav_drawer_header, null, false);
mNavDrawerAvatarImageView = (ImageView) header.findViewById(R.id.avatar);
mNavDrawerUsernameTextView = (CustomTextView) header.findViewById(R.id.username);
navDrawerListView.addHeaderView(header);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
getToolbar(),
R.string.navigation_drawer_open,
R.string.navigation_drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
updateNavDrawerUserInfo();
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mNavDrawerAdapter = new NavDrawerAdapter(this);
navDrawerListView.setAdapter(mNavDrawerAdapter);
navDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
mDrawerLayout.closeDrawer(GravityCompat.START);
onNavigationDrawerItemSelected(position);
}
});
updateNavDrawerUserInfo();
}
private void updateNavDrawerUserInfo() {
final DatabaseHelper db = DatabaseHelper.getInstance(this);
if (db.doesUserExist(SharedPrefs.getUserId())) {
final User currentUser = db.getUser(SharedPrefs.getUserId());
if (currentUser != null) {
if (currentUser.getAvatarType() != null) {
try {
mNavDrawerAvatarImageView.setImageDrawable(getResources().getDrawable(
ViewUtil.getAvatarHeadDrawableId(this,
currentUser.getAvatarType())));
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
}
if (currentUser.getUsername() != null) {
mNavDrawerUsernameTextView.setText(currentUser.getUsername());
}
}
}
}
}
BaseActivity
private void setupToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("");
getSupportActionBar().setSubtitle("");
getSupportActionBar().setLogo(R.drawable.logo_toolbar);
}
mUpdatingSpinner = (ProgressBar) getLayoutInflater().inflate(
R.layout.toolbar_updating_spinner, null, false);
int dpInPixels = (int) getResources().getDimension(R.dimen.toolbar_updating_spinner);
Toolbar.LayoutParams spinnerLp = new Toolbar.LayoutParams(dpInPixels, dpInPixels,
Gravity.END);
mToolbar.addView(mUpdatingSpinner, spinnerLp);
}
I found the answer although I don't fully understand it.
I basically called setupToolbar() again in my BaseDrawerActivity right before I call setupNavDrawer() and for some reason this fixed it.
I think the reference to the Toolbar from BaseActivity wasn't retrieving correctly (even though I debugged and it had a reference to it). Another thing I tried is setSupportActionBar(mToolbar) right before setting up the nav drawer but that didn't work.
If anyone has any ideas as to why I have to setup the toolbar again in order for it to show I'd be glad to hear it!
go to the AndroidManifest.xml file and replace
android:theme="#style/AppTheme"
with
android:theme="#android:style/Theme.Holo.Light.DarkActionBar"
you have to use setSupportActionBar(Toolbar toolbar).
This question should help.
I followed the android guideline and completed a layout looks like this:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id= "#+id/my_awesome_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/fragmentContainer"/>
</LinearLayout>
<LinearLayout
android:id="#+id/left_drawer_view"
android:layout_width="250dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="start">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/wall"
android:layout_margin="0dp"
android:padding="0dp"
android:scaleType="center"
/>
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/placeholder"
android:layout_margin="16dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IGuessI'mUsername?"
android:textColor="#fff"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_margin="10dp"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:orientation="vertical"
android:background="#fff"
android:id="#+id/left_drawer_item"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/side_item_home"
android:text="Home"
android:drawablePadding="5dp"
android:padding="5dp"
android:gravity="center_vertical"
android:drawableLeft="#drawable/ic_menu_home"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Activities"
android:drawablePadding="5dp"
android:id="#+id/side_item_activities"
android:padding="5dp"
android:gravity="center_vertical"
android:drawableLeft="#drawable/ic_menu_search_holo_light"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Settings"
android:drawablePadding="5dp"
android:id="#+id/side_item_settings"
android:padding="5dp"
android:gravity="center_vertical"
android:drawableLeft="#drawable/ic_action_settings"
/>
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
FYI, I did not use Android.R.Id, but my own R.id.fragmentContainer to load the fragments. But apparently, the drawer layout is under the fragment loaded in the FrameLayout. If I click the item on the DrawerLayout, the fragments receive the gesture, not the DrawerLayout, although it still display correctly.
I need your two cents, guys. All answers and comments are appreciated.
Edit:
Here is the requested code.
public class ClipMe_main extends ActionBarActivity implements View.OnClickListener {
private HashMap<String, Stack<Fragment>> mStacks;
SlidingTabFragment homeFragment;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private String[] mTitle;
Fragment settingsFragment;
private ArrayList<DrawerItemModel> drawerData;
android.support.v7.app.ActionBar bar;
ActionBarDrawerToggle mDrawerToggle;
SlidingTabLayout mSlidingTabLayout;
public static DisplayMetrics displayMetrics;
FragmentManager fm;
FragmentPagerAdapter adapterViewPager;
int visiblePage;
TextView sideBarHome;
TextView sideBarActivities;
TextView sideBarSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main_activity);
displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(displayMetrics);
registerReceiver(receiverDownloadComplete, new IntentFilter(DownloadService.ACTION_DOWNLOAD_COMPLETE));
sideBarHome = (TextView) findViewById(R.id.side_item_home);
sideBarActivities = (TextView) findViewById(R.id.side_item_activities);
sideBarSettings = (TextView) findViewById(R.id.side_item_settings);
sideBarSettings.setOnClickListener(this);
sideBarHome.setOnClickListener(this);
sideBarActivities.setOnClickListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
new Toolbar(ClipMe_main.this),
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(getTitle());
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(getTitle());
}
};
setUpView();
setUpHomeFragment();
setUpSettingFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
toolbar.setBackgroundColor(getResources().getColor(R.color.swipe_refresh_2));
setSupportActionBar(toolbar);
mDrawerLayout.setDrawerListener(mDrawerToggle);
bar = this.getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
bar.setDisplayShowTitleEnabled(true);
}
private void setUpSettingFragment() {
settingsFragment = new SettingsFragment();
}
void setUpView() {
setContentView(R.layout.layout_main_activity);
}
void setUpHomeFragment() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
homeFragment = new SlidingTabFragment();
transaction.add(R.id.fragmentContainer, homeFragment, "home");
transaction.commit();
}
public void pushFragments(String tag, Fragment fragment, boolean shouldAnimate) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (shouldAnimate)
ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
ft.replace(R.id.fragmentContainer, fragment, tag).addToBackStack(null);
ft.commit();
Log.d("FragmentManager", "Push " + tag);
}
public void getFragmentAndUpdate(int page) {
PopularFragment currentFragment = homeFragment.getCurrentFragment();
currentFragment.requestMoreData(page);
Log.d("FragmentPage", String.valueOf(page));
}
#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_clipme_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.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int id = item.getItemId();
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public int findVisibleFragment(){
Fragment homeFragment = (Fragment) getSupportFragmentManager().findFragmentByTag("home");
Fragment activitiesFragment = (Fragment) getSupportFragmentManager().findFragmentByTag("activities");
Fragment settingsFragment = (Fragment) getSupportFragmentManager().findFragmentByTag("settings");
Fragment likeFragment = (Fragment) getSupportFragmentManager().findFragmentByTag("like");
Fragment commentFragment = (Fragment) getSupportFragmentManager().findFragmentByTag("comment");
if(homeFragment!= null && homeFragment.isVisible()){
return 1;
} else if(activitiesFragment!= null && activitiesFragment.isVisible()){
return 2;
} else if (settingsFragment!= null && settingsFragment.isVisible()){
return 3;
} else if (likeFragment!= null && likeFragment.isVisible()){
return 4;
} else if (commentFragment!= null && commentFragment.isVisible()){
return 5;
} else
return 0;
}
#Override
public void onClick(View v) {
if (v == sideBarHome){
if (findVisibleFragment() == 1){
mDrawerLayout.closeDrawers();
} else {
mDrawerLayout.closeDrawers();
pushFragments("activities", homeFragment, true);
}
}
if (v == sideBarActivities){
if (findVisibleFragment() == 2){
mDrawerLayout.closeDrawers();
} else {
mDrawerLayout.closeDrawers();
pushFragments("activities", new ActivitiesFragment(), true);
}
}
if (v == sideBarSettings){
if (findVisibleFragment() == 1){
mDrawerLayout.closeDrawers();
} else {
mDrawerLayout.closeDrawers();
pushFragments("activities", settingsFragment, true);
}
}
}
}
The issue i found is in the onClick() method. Try changing the function as below
public Fragment findVisibleFragment() {
FragmentManager manager = getSupportFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.fragmentContainer);
return fragment;
}
Edit:
set the same listener to multiple views.
sideBarHome.setOnClickListener(clickListener);
sideBarSettings.setOnClickListener(clickListener);
Refer this clicklistener object to the view and you can use the same logic to differentiate views
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view.getId() == R.id.side_item_home) {
// mDrawerLayout.closeDrawers();
if (!(findVisibleFragment() instanceof SlidingTabFragment)) {
pushFragments("activities", homeFragment, true);
}
}
else if() {
//rest click logic
}
}
};