cannot resolve symbol 'toolbar' r.id.toolbar [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
i'm trying to create a sliding drawer. I spent forever getting my imports to match my code, in terms of getSupportActionBar vs getActionBar etc., I suspect the issue is somewhere in the activity_main.xml but I'm at a loss for what to put there.
MainActivity.java
package me.paxana.alerta;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.app.Fragment;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import me.paxana.alerta.adapter.SlidingMenuAdapter;
import me.paxana.alerta.fragment.Fragment1;
import me.paxana.alerta.fragment.Fragment2;
import me.paxana.alerta.fragment.Fragment3;
import me.paxana.alerta.model.ItemSlideMenu;
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private List<ItemSlideMenu> listSliding;
private SlidingMenuAdapter adapter;
private ListView listViewSliding;
private DrawerLayout drawerLayout;
private android.support.v7.app.ActionBarDrawerToggle actionBarDrawerToggle;
private Toolbar mToolbar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null) {
navigateToLogin();
}
else {
Log.i(TAG, currentUser.getUsername());
}
listViewSliding = (ListView)findViewById(R.id.lv_sliding_menu);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
listSliding = new ArrayList<>();
//add item for sliding list
listSliding. add(new ItemSlideMenu(R.drawable.ic_action_settings, "Settings"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_about, "About"));
listSliding.add(new ItemSlideMenu(R.mipmap.ic_launcher, "Android"));
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//display icon to open/close slider
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
assert getActionBar() != null;
getActionBar().setDisplayHomeAsUpEnabled(true);
//set title
setTitle(listSliding.get(0).getTitle());
//item selected
listViewSliding.setItemChecked(0, true);
//close menu
drawerLayout.closeDrawer(listViewSliding);
//handle on item click
listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//set title
setTitle(listSliding.get(position).getTitle());
//item selected
listViewSliding.setItemChecked(position, true);
//close menu
drawerLayout.closeDrawer(listViewSliding);
}
});
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_opened, R.string.drawer_closed) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int itemId = item.getItemId();
if (itemId == R.id.action_logout) {
ParseUser.logOut();
navigateToLogin();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
//create method replace fragment
private void replaceFragment(int pos) {
android.support.v4.app.Fragment fragment = null;
switch (pos) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
default:
fragment = new Fragment1();
break;
}
if(null != fragment) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
tools:context="me.paxana.alerta.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_content">
</RelativeLayout>
<ListView
android:layout_width="200dp"
android:layout_height="match_parent"
android:id="#+id/lv_sliding_menu"
android:background="#FFFFFF"
android:choiceMode="singleChoice"
android:layout_gravity="start" />
</android.support.v7.widget.Toolbar>

Why are you using android.support.v7.widget.Toolbar for your main_layout root tag? That's not what android says.
You should use that Toolbar just for using Toolbar with your activity.
See: setContentView(R.layout.activity_main);
That won't work at all.
Use it like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context="me.paxana.alerta.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/ColorPrimary"
app:layout_collapseMode="pin"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<ListView
android:id="#+id/lv_sliding_menu"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFFFFF"
android:choiceMode="singleChoice" />
</RelativeLayout>
I'd rather to use CoordinatorLayout with AppCompat or this Toolbar implementation too.
Also,
//display icon to open/close slider
mToolbar = (Toolbar) findViewById(R.id.toolbar);
Here you were using toolbar as that Toolbar id.
Use it like this in your xml:
android:id="#+id/toolbar"
Above code should work now.Also, you've many not used in your imports like:
import android.support.v7.app.ActionBarActivity;
and etc.
Read the docs please.

Use this
R.id.drawer_layout
Instead of
R.id.toolbar

Related

Where do I put the nav_host portion of the xml code?

I am trying to figure out where I should be putting the nav_host in my xml files. I am not fully understanding how to get around my application fragments in general.
I have read this Add Drawer layout into main activity
I had most of this working before trying to add the Navigation host (Meaning I could use the drawer menu and navigate). I have not been able to navigate from a fragment to anywhere else with a button that is on that fragment.
My current activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<androidx.fragment.app.FragmentContainerView
android:id="#+id/mainActivityHost"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation"
tools:layout="#layout/fragment_home" />
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/drawer_menu"/>
</androidx.drawerlayout.widget.DrawerLayout>
Is where I have the nav_host correct? Or should I have a different Fragment all together for the nav_host?
My MainActivity.class
package com.signin.app;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.android.material.navigation.NavigationView;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// The program should always start on home.
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.mainActivityHost, new HomeFragment()).commit();
navigationView.setCheckedItem(R.id.nav_home);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
} else if (id == R.id.nav_signin) {
} else if (id == R.id.nav_flights) {
} else if (id == R.id.nav_hotels) {
} else if (id == R.id.nav_profile) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//
// #Override
// public void onBackPressed() {
// if (drawer.isDrawerOpen(GravityCompat.START)) {
// drawer.closeDrawer(GravityCompat.START);
// } else {
// super.onBackPressed();
// }
// }
}
Before I messed with it I could open the drawer click the menu items and go to a fragment, so pretending that still worked the problem was that I could go to Signin fragment, but the buttons on that fragment would not take me anywhere, they mostly just crashed the application.
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
public class SigninFragment extends Fragment {
private EditText editText;
private Button btn_signup, btn_signin, btn_forgot_pass;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container,false);
editText = view.findViewById(R.id.email);
btn_signup = view.findViewById(R.id.btn_signup);
btn_signin = view.findViewById(R.id.btn_signin);
btn_forgot_pass = view.findViewById(R.id.btn_forgot_pass);
btn_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(getContext(), "Sign Up", Toast.LENGTH_SHORT).show();
Navigation.findNavController(view).navigate(R.id.nav_signup);
}
});
btn_signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Sign in", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}```
Also, please note that nav_signup is not in the drawer menu so I wasn't sure where I was supposed to identify it, (i.e., in the fragment_signup.xml, in its own menu, somewhere else.) right now the id for fragment_signup, is `android:id="#+id/nav_signup"`
I'm not sure I understand the question
Navigation.findNavController(view).navigate(R.id.nav_signup); - it should do the navigation and R.id.nav_signup should be destination or action. I'm not sure what R.id.nav_signup is atm. If destination then probably it should be fragment id.
Here's doc about navigations https://developer.android.com/guide/navigation/navigation-navigate#java
And here is Google course about navigation between fragments https://developer.android.com/codelabs/basic-android-kotlin-training-fragments-navigation-component#6 (This guide is in Kotlin but that's just a syntax difference, hopefully still can be useful)
And the final code of this is here https://github.com/google-developer-training/android-basics-kotlin-words-app (it uses navigation/nav_graph.xml to define navigations between fragments)
And for example in src/main/java/com/example/wordsapp/LetterAdapter.kt has navigation to different fragment.
holder.button.setOnClickListener {
// LetterListFragmentDirections is defined in nav_graph.xml
val action = LetterListFragmentDirections.actionLetterListFragmentToWordListFragment(letter = holder.button.text.toString())
// Navigate using that action
holder.view.findNavController().navigate(action)
}
I haven't used fragments a long time, but I hope this will be helpful :)

how to make android app in java using navigation drawer and viewpager/viewpager2

hello I am making an application to debate in android studio using Java, I intend that the application occupies a navigation drawer and a viewpager / viewpager2. I am very new programming in androidstudio and therefore I have followed several video tutorials to incorporate viewpager / viepager 2 with navigation drawer but so far none works for me (the navigation drawer only works for me), the last thing I tried was to use viewpager (since with viepager 2 I had problems calling the adapter from the main), but when compiling the project the emulator was I was left with a black screen and it did not show anything. I hope you can help me because this project is very important to me. Here is part of my code:
main:
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import Fragments.generaDebate;
import Fragments.perfil_user;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
Toolbar toolbar;
NavigationView navigationView;
//variables para cargar el fragment
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
String personName;
//variable viewpager
ViewPager pager;
TabLayout tablayout;
TabItem first_item,second_item;
pageAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);//se pasa el toolbar
drawerLayout=findViewById(R.id.drawer);
navigationView=findViewById(R.id.navigationView);
navigationView.setNavigationItemSelectedListener(this);
actionBarDrawerToggle=new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.open,R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
actionBarDrawerToggle.syncState();
//carga viewpager
pager=findViewById(R.id.view);
tablayout=findViewById(R.id.title_menu);
first_item=findViewById(R.id.first_item);
second_item=findViewById(R.id.second_item);
//declarando adapter en el main
FragmentManager fragmentManager;
fragmentManager=getSupportFragmentManager();
adapter=new pageAdapter(fragmentManager, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,tablayout.getTabCount());
pager.setAdapter(adapter);
tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
pager.addOnAdapterChangeListener((ViewPager.OnAdapterChangeListener) new TabLayout.TabLayoutOnPageChangeListener(tablayout));
//cargar fragment principal
FragmentTransaction fragmentTransaction;
fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, new perfil_user());
fragmentTransaction.commit();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.user){
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
fragmentManager=getSupportFragmentManager();
fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, new perfil_user());
fragmentTransaction.commit();
}
else if (item.getItemId() == R.id.exit){
//finish();
loggin login=new loggin();
login.signOut();
}
//aquí van las otros fragment
drawerLayout.closeDrawer(GravityCompat.START);
return false;
}
}
adapter:
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.ArrayList;
import Fragments.generaDebate;
import Fragments.perfil_user;
public class pageAdapter extends FragmentPagerAdapter {
private int tabsNumber;
public pageAdapter(#NonNull FragmentManager fm, int behavior,int tabs) {
super(fm, behavior);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 1:
return new perfil_user ();
case 2:
return new generaDebate();
default:
return null;
}
}
#Override
public int getCount() {
return tabsNumber;
}
}
The navigation drawer is the most common feature offered by android and the navigation drawer is a UI panel that shows your app’s main navigation menu. It is also one of the important UI elements, which provides actions preferable to the users like example changing user profile, changing settings of the application, etc. In this article, it has been discussed step by step to implement the navigation drawer in android
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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:background="#color/bgColor"
android:layout_height="match_parent"
tools:context=".activities.MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:gravity="center_vertical"
android:background="#color/bgColor"
android:paddingStart="20dp"
android:paddingEnd="20dp"
android:orientation="horizontal">
</LinearLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/vp_horizontal_ntb"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
android:foreground="?attr/selectableItemBackground"
app:menu="#menu/bottom_navigation"
app:elevation="10dp"
app:labelVisibilityMode="labeled"
app:itemIconTint="#color/bottom_navigation_color"
app:itemTextColor="#color/bottom_navigation_color"
app:itemBackground="#color/bottomNavigationBackground"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigationMenu"
android:icon="#android:drawable/ic_menu_sort_by_size"
android:title="Menu" />
<item
android:id="#+id/navigationMyCourses"
android:icon="#drawable/ic_email"
android:title="Courses" />
<item
android:id="#+id/navigationHome"
android:icon="#drawable/ic_home"
android:title="Home" />
<item
android:id="#+id/m_refer"
android:icon="#android:drawable/ic_menu_share"
android:title="Refer" />
<item
android:id="#+id/navigationMyProfile"
android:icon="#drawable/ic_back"
android:title="User" />
</menu>
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(#NonNull #NotNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull
#NotNull
#Override
public Fragment createFragment(int p) {
switch (p) {
case 0:
return new ProfileFragment();
case 1:
return new LeaderBoardFragment();
case 2:
return new HomeFragment();
case 3:
return new ReferFragment();
case 4:
return new ProfileFragment();
default:
return new HomeFragment();
}
}
#Override
public int getItemCount() {
return 5;
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
this.viewPager2 = findViewById(R.id.vp_horizontal_ntb);
viewPager2.setOffscreenPageLimit(100);
this.bottomNavigationView = findViewById(R.id.navigation);
adapter = new ViewPagerAdapter(this);
viewPager2.setAdapter(adapter);
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
switch (position) {
case 0:
bottomNavigationView.getMenu().findItem(R.id.navigationMenu).setChecked(true);
break;
case 1:
bottomNavigationView.getMenu().findItem(R.id.navigationMyCourses).setChecked(true);
break;
case 2:
bottomNavigationView.getMenu().findItem(R.id.navigationHome).setChecked(true);
break;
case 3:
bottomNavigationView.getMenu().findItem(R.id.m_refer).setChecked(true);
break;
case 4:
bottomNavigationView.getMenu().findItem(R.id.navigationMyProfile).setChecked(true);
break;
}
}
});
bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
#SuppressLint("NonConstantResourceId")
#Override
public boolean onNavigationItemSelected(#NonNull #NotNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigationHome:
viewPager2.setCurrentItem(2);
break;
case R.id.navigationMyProfile:
viewPager2.setCurrentItem(4);
break;
case R.id.m_refer:
viewPager2.setCurrentItem(3);
break;
case R.id.navigationMyCourses:
viewPager2.setCurrentItem(1);
break;
case R.id.navigationMenu:
viewPager2.setCurrentItem(0);
break;
}
return false;
}
});
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) bottomNavigationView.getLayoutParams();
layoutParams.setBehavior(new BottomNavigationBehavior());
bottomNavigationView.setSelectedItemId(R.id.navigationMenu);
}
}
Happy Coding

cannot set tab layout inside fragment

I am trying to set a tab layout inside a fragment and call it by an option inside navigation drawer but I am getting a null object reference error.
I am setting my navigation drawer inside Main2Activity
Main2Activity
import android.content.Intent;
import android.os.Bundle;
import com.bumptech.glide.Glide;
import com.example.fireapp.model.Users;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Layout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.example.fireapp.ui.main.SectionsPagerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class Main2Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private View headerView;
private TextView usernameText;
private TextView emailText;
private CircleImageView userImage;
private FirebaseUser firebaseUser;
private DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("fireApp");
//navigation drawer
drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
//user details
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
headerView = navigationView.getHeaderView(0);
usernameText = headerView.findViewById(R.id.usernameText);
userImage = headerView.findViewById(R.id.userImage);
emailText = headerView.findViewById(R.id.userEmail);
setUserDetails();
// if(savedInstanceState==null) {
// getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
// new chatFragment()).commit();
// navigationView.setCheckedItem(R.id.nav_chat);
// }
}
private void setUserDetails() {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("User").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Users user = dataSnapshot.getValue(Users.class);
usernameText.setText(user.getUsername());
emailText.setText(firebaseUser.getEmail());
if (user.getImageUrl().equals("default")) {
userImage.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(getApplicationContext()).load(user.getImageUrl()).into(userImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch(menuItem.getItemId()){
case R.id.nav_chat:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new chatFragment()).commit();
break;
case R.id.nav_share:
Toast.makeText(this, "Share!", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_feedback:
Toast.makeText(this, "Feedback!", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//3 dots menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.logout) {
AuthUI.getInstance()
.signOut(Main2Activity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(Main2Activity.this, MainActivity.class));
finish();
}
});
return true;
} else
return false;
}
}
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<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_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".Main2Activity"
tools:openDrawer="end">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer_menu"></com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
chatFragment
package com.example.fireapp;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.fireapp.ui.main.SectionsPagerAdapter;
import com.google.android.material.tabs.TabLayout;
public class chatFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_chat,container,false);
tabLayout=view.findViewById(R.id.tabs);
viewPager=view.findViewById(R.id.view_pager);
viewPager.setAdapter(new SectionsPagerAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
}
fragment_chat.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".chatFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</FrameLayout>
SectionPagerAdapter
package com.example.fireapp.ui.main;
import android.content.Context;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.fireapp.R;
import com.example.fireapp.tab1;
import com.example.fireapp.tab2;
import com.example.fireapp.tab3;
import java.util.List;
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2,R.string.tab_text_3};
private Context mContext ;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
public SectionsPagerAdapter(FragmentManager childFragmentManager) {
super(childFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0 :
tab1 tab1 = new tab1();
return tab1;
case 1:
tab2 tab2 = new tab2();
return tab2;
case 2:
tab3 tab3 = new tab3();
return tab3;
}
return null;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
I am getting the following error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fireapp, PID: 6785
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at com.example.fireapp.ui.main.SectionsPagerAdapter.getPageTitle(SectionsPagerAdapter.java:61)
at com.google.android.material.tabs.TabLayout.populateFromPagerAdapter(TabLayout.java:1323)
at com.google.android.material.tabs.TabLayout.setPagerAdapter(TabLayout.java:1314)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1227)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1188)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1168)
at com.example.fireapp.chatFragment$1.run(chatFragment.java:32)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
I am new to android development please help.
java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.Resources android.content.Context.getResources()'
on a null object reference
NullPointerException is thrown when an application attempts to use an object reference that has the null value.
You can try with this
private String TAB_TITLES[] = new String[]{"Tab1", "Tab2", "Tab3"};
Then
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return TAB_TITLES[position];
}
getPageTitle() - This method may be called by the ViewPager to obtain a title string to describe the specified page.

use navigation drawer in all activities in my project

I have created a navigation drawer in my AbstractActivity.class and i want to use that drawer in all my activities , so i created another drawer class and extending that class in another activity but it isnt working , can anyonetell me whats wrong in my code ?
Abstractactivity.class
package com.astro.famouspandit.Activities.Abstract;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Image;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.astro.famouspandit.Activities.Activity.ChartStyle;
import com.astro.famouspandit.Activities.Activity.Contact;
import com.astro.famouspandit.Activities.Activity.Settings;
import com.astro.famouspandit.Activities.Activity.Welcome;
import com.astro.famouspandit.R;
public class AbstractActivity extends AppCompatActivity {
private String[] mPlanetTitles;
private LinearLayout mDrawerList;
protected DrawerLayout mDrawerLayout;
protected ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
protected Toolbar toolbar;
protected FrameLayout framelayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_abstract);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (LinearLayout) findViewById(R.id.left_drawer);
framelayout = (FrameLayout)findViewById(R.id.content_frame);
mTitle = mDrawerTitle = getTitle().toString();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
toolbar, R.string.drawer_open, R.string.drawer_close){
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
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_Aboutus).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void selectItem(int position) {
switch(position) {
case 1:
Intent a = new Intent(this, Welcome.class);
startActivity(a);
break;
case 2:
Intent b = new Intent(this, Welcome.class);
startActivity(b);
break;
default:
}
}
public boolean onOptionsItemSelected(MenuItem item){
int items = item.getItemId();
switch(items){
case R.id.action_Settings:{
Intent intent = new Intent(this,Settings.class);
startActivity(intent);
}break;
case R.id.action_Contact_us:{
Intent intent = new Intent(this,Contact.class);
startActivity(intent);
}break;
case R.id.action_Aboutus:{
Intent intent = new Intent(this,ChartStyle.class);
startActivity(intent);
}break;
case R.id.action_Profile:{
Intent intent = new Intent(this,ChartStyle.class);
startActivity(intent);
}break;
}
return super.onOptionsItemSelected(item);
}
}
activity_abstract.xml
<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">
<include layout="#layout/toolbar"/>
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<LinearLayout android:id="#+id/left_drawer"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#0F6177">
<LinearLayout android:id="#+id/view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="#layout/navigation_drawer"></include>
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
NavigationActivity.class
package com.astro.famouspandit.Activities.Abstract;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.astro.famouspandit.R;
public abstract class NavigationActivity extends AppCompatActivity implements View.OnClickListener{
protected DrawerLayout mDrawerLayout;
private LinearLayout mFrameLayout_HeaderView;
protected FrameLayout mFrameLayout_ContentFrame;
protected ActionBarDrawerToggle mActionBarDrawerToggle;
protected Toolbar mToolbar;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
mFrameLayout_ContentFrame = (FrameLayout) findViewById(R.id.main_activity_content_frame);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mFrameLayout_HeaderView = (LinearLayout) findViewById(R.id.mainLayout);
mFrameLayout_HeaderView.setOnClickListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.main_activity_DrawerLayout);
mDrawerLayout.closeDrawers();
mDrawerLayout.setStatusBarBackground(R.color.colorPrimary);
mActionBarDrawerToggle = new ActionBarDrawerToggle
(
this,
mDrawerLayout,
mToolbar,
R.string.drawer_open,
R.string.drawer_close
) {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Disables the burger/arrow animation by default
super.onDrawerSlide(drawerView, 0);
}
};
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
mActionBarDrawerToggle.syncState();
}
}
activity_navigationactivity.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_activity_DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- The main content view -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/main_activity_content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer -->
<include layout="#layout/navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
class where i am extending NavigationActivity Class
public class Welcome extends NavigationActivity implements View.OnClickListener{
private CardView mAstro,mMatch,mPanch,mAsk,mContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_welcome,mFrameLayout_ContentFrame);
This is a fairly common question has been blogged about. Essentially, you want to create a BaseActivity with a layout that contains the Navigation Drawer and then have your other Activities extend the BaseActivity and inflate their layouts within the BaseActivity's layout. This way you have the Navigation Drawer in all your activity and reuse the code for setting up the Drawer (since that code lives in the BaseActivity).
You can find an example implementation along with a more detailed explanation here: http://lucas-dev.com/blog/entry/base-activities-sliding-menu.html

Why does this Navigation Drawer not open?

I'm trying to make a Navigation Drawer, I'm reading a lot of guides on how to do this and I think it should work now, but the Drawer does not open when I click on the title (when I manually try to open it, then the icon will get smaller, but still no menu appears). Also, I'm not getting any errors or exception, so I think I might be missing something which I cannot figure out myself.
This is the code of my BaseActivity (the drawer activity which gets extended by my MainActivity):
import android.os.Bundle;
import android.app.Activity;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class BaseActivity extends Activity {
public DrawerLayout drawerLayout;
public ListView drawerList;
private String[] drawerListEntries;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
drawerListEntries = getResources().getStringArray(R.array.drawer_items);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_navigation_drawer, R.string.drawer_open, R.string.drawer_close)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(R.string.hello_world);
}
};
drawerLayout.setDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
drawerList = (ListView) findViewById(R.id.drawer_list);
drawerList.setAdapter(new ArrayAdapter<String>(getBaseContext(), R.layout.drawer_list_item, drawerListEntries));
drawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int pos, long arg3) {
String selectedValue = (String) drawerList.getAdapter().getItem(pos);
Toast.makeText(getBaseContext(), selectedValue, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = drawerLayout.isDrawerOpen(drawerList);
menu.findItem(R.id.action_user).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
}
This is my activity_base.xml:
<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">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/drawer_list"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:background="#color/light_blue"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:choiceMode="singleChoice"
android:layout_gravity="start"
/>
</android.support.v4.widget.DrawerLayout>
This is my drawer_list_item.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="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/drawer_list_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="12dp"
android:textSize="24sp"
android:textColor="#color/belize_hole"
android:fontFamily="sans-serif-light">
</TextView>
</LinearLayout>
And this is my MainActivity.java which extends BaseActivity:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class HomeActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
//return super.onCreateOptionsMenu(menu);
return true;
}
}
Anyone who can see the problem?
You are overriding content view from BaseActivity by calling setContentView(R.layout.activity_home); in HomeActivity.
I suggest you to switch fragments instead of activities with Navigation Drawer, it's the best way. So you will have one hosting activity with Navigation Drawer and you'll switch only views inside FrameLayout, for instance. Take a look here http://developer.android.com/training/implementing-navigation/nav-drawer.html

Categories