In my one of my fragments I have a toggle button in the xml:
<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"
tools:context="com.stefan.findage.piano">
<!-- TODO: Update blank fragment layout -->
<ToggleButton
android:id="#+id/metronome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />
</FrameLayout>
And
toggleButton = (ToggleButton) getView().findViewById(R.id.metronome);
But when trying to open the fragment it crashes and the logcat shows that it was a
java.lang.NullPointerException:Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
Here's the Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.bottomView);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.moosic:
rhythm fragmentone = new rhythm();
android.support.v4.app.FragmentTransaction fragmentTransaction3 = getSupportFragmentManager().beginTransaction();
fragmentTransaction3.replace(R.id.frame, fragmentone, "rhythm");
fragmentTransaction3.commit();
return true;
case R.id.call:
intervals fragmenttwo = new intervals();
android.support.v4.app.FragmentTransaction fragmentTransaction2 = getSupportFragmentManager().beginTransaction();
fragmentTransaction2.replace(R.id.frame, fragmenttwo, "intervals");
fragmentTransaction2.commit();
return true;
case R.id.thinga:
piano fragmentthree = new piano();
android.support.v4.app.FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.frame, fragmentthree, "piano");
fragmentTransaction1.commit();
return true;
}
return false;
}
});
}
}
getView() might be returning null. Use the below code to reference the toggle button
View view = inflater.inflate(R.layout.fragmentlayout, container, false);
toggleButton = (ToggleButton) view.findViewById(R.id.metronome);
Related
I'm trying to achieve Fragment to Fragment transaction with onOptionsItemSelected but I keep getting
java.lang.IllegalArgumentException: No view found for id
I also read this thread:
Android Fragment no view found for ID? and applied some answer to my code but it is not solve my problem
Here is my HomeFragment.java
private Toolbar toolbar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//Set Toolbar for Fragment
View v = inflater.inflate(R.layout.fragment_home, container, false);
toolbar = (Toolbar) v.findViewById(R.id.main_toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
setHasOptionsMenu(true);
return v;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.toolbar_menu,menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
FragmentManager fm = getActivity().getSupportFragmentManager();
fm.beginTransaction().replace(R.id.cart_fragment_layout,new CartFragment())
.commitNow();
return super.onOptionsItemSelected(item);
}
}
My fragment_cart.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"
android:id="#+id/cart_fragment_layout"
tools:context="com.example.fragment.CartFragment"
android:background="#color/black">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:orientation="vertical"
android:id="#+id/cart_ll"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/cart_rv"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#color/white"
android:textSize="50dp"
android:text="Cart Fragment" />
</LinearLayout>
</FrameLayout>
and my CartFragment.java
public class CartFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_cart, container, false);
return v;
}
}
My MainActivity.java just in case, I set HomeFragment as default:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
toolbar = findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.frament_container,
new HomeFragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()){
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_menu:
selectedFragment = new MenuFragment();
break;
case R.id.nav_user:
selectedFragment = new UserFragment();
break;
case R.id.nav_more:
selectedFragment = new MoreFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frament_container,
selectedFragment).commit();
return true;
}
};
}
The id you use in a fragment transaction is NOT the view id of a view in the fragment. Its the id of the fragment stub view in the layout you're popping the fragment into. So you're passing in the wrong id. I can't tell you what the right one is, as you don't give us the xml of your main layout.
Basically the fragment transaction looks for the id you pass out in the context root layout, then pops out what's already there and replaces it with your fragment.
I need to stop each fragment from refreshing when selected from the bottom menu. There is loads of similar questions on here but being new to Android development I can't seem to get any to work. I think I know why it's happening (I believe I'm calling return new for each fragment) but unsure how to implement slightly different coding. In summary, I need each tab to load a WebView when first clicked then remain in that state until the user clicks a link within that view or closes the App.
MainActivity.java
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
private BottomNavigationView mBottomNavigation;
private ViewPager viewPager;
private ViewPagerAdapter mViewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new HomeFragment());
mBottomNavigation = findViewById(R.id.nav_view);
mBottomNavigation.setOnNavigationItemSelectedListener(this);
viewPager = findViewById(R.id.view_pager);
mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mViewPagerAdapter);
viewPager.setOffscreenPageLimit(5);
}
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment);
ft.commit();
return true;
}
return false;
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()) {
case R.id.navigation_news:
fragment = new HomeFragment();
break;
case R.id.navigation_scheduled:
fragment = new DashboardFragment();
break;
case R.id.navigation_LIVE:
fragment = new NotificationsFragment();
break;
case R.id.navigation_results:
fragment = new ResultsFragment();
break;
case R.id.navigation_help:
fragment = new HelpFragment();
break;
}
return loadFragment(fragment);
}}
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position){
switch (position) {
case 0:
return new HomeFragment();
case 1:
return new DashboardFragment();
case 2:
return new NotificationsFragment();
case 3:
return new ResultsFragment();
case 4:
return new HelpFragment();
}
return null;
}
#Override
public int getCount(){
return 5;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="0dp">
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/view_pager"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:labelVisibilityMode="labeled"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
/>
<fragment
android:id="#+id/nav_host_fragment_activity_main"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#+id/nav_view"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.091"
app:navGraph="#navigation/mobile_navigation"
tools:layout_editor_absoluteX="9dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
HomeFragment.java
public class HomeFragment extends Fragment {
private HomeViewModel HomeViewModel;
private FragmentHomeBinding binding;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
String url = "https://www.google.com";
WebView view = (WebView)rootView.findViewById(R.id.webviewnews);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new WebViewClient());
view.loadUrl(url);
return rootView;
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
Thank you in advance.
I guess that the problem here is the recreation of every fragment everytime ViewPagerAdapter.getItem gets called. Each time you click on an item, you create a new fragment. It won't just reload, it's actually a very new and fresh fragment without anything.
Try to lazily instantiate your fragments like below:
private HomeFragment homeFragment = null;
public Fragment getItem(int position){
switch (position) {
case 0:
if(homeFragment == null) homeFragment = new HomeFragment();
return homeFragment;
// Other cases
This will not only help your problem, but also uses less memory and puts less pressure on GC.
Also, after your replacements, your fragments' onResume will be called (just in case if you need to do something you can do that in onResume)
you are replacing fragment when loading fragment, so as soon as you will call replace fragment it will recreate fragment and onCreate will be called so in respect of replacing use add fragment that will not reload fragment again and again
I am developing news app and I have implemented navigation drawer
using following link but when I run the code app showing empty white
screen.
below my MainActivity.java class
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Inflate the header view at runtime
View headerLayout = nvDrawer.inflateHeaderView(R.layout.nav_header);
// We can now look up items within the header if needed
#SuppressLint("ResourceType") ImageView ivHeaderPhoto = headerLayout.findViewById(R.drawable.ic_sportnews);
setupDrawerContent(nvDrawer);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
menuItem -> {
selectDrawerItem(menuItem);
return true;
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass = null;
switch (menuItem.getItemId()) {
case R.id.bbcsports_fragment:
fragmentClass = BBCSportFragment.class;
break;
case R.id.talksports_fragment:
fragmentClass = TalkSportsFragment.class;
break; case R.id.foxsports_fragment:
fragmentClass = FoxSportsFragment.class;
break;
default:
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
mDrawer.closeDrawers();
}
}
below my activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
app:headerLayout="#layout/nav_header"
app:menu="#menu/navigation_menu" />
</android.support.v4.widget.DrawerLayout>
below my Fragment class
public class BBCSportFragment extends Fragment {
public List<Article> articleList = new ArrayList<Article>();
#BindView(R.id.recycler_view)
RecyclerView recyclerView;
private SportNews sportNews;
private ArticleAdapter articleAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_bbcsport, container, false);
ButterKnife.bind(this, view);
SportInterface sportInterface = SportClient.getApiService();
Call<SportNews> call = sportInterface.getArticles();
call.enqueue(new Callback<SportNews>() {
#Override
public void onResponse(Call<SportNews> call, Response<SportNews> response) {
sportNews = response.body();
if (sportNews != null && sportNews.getArticles() != null) {
articleList.addAll(sportNews.getArticles());
}
articleAdapter = new ArticleAdapter(articleList, sportNews);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(articleAdapter);
}
#Override
public void onFailure(Call<SportNews> call, Throwable t) {
}
});
return view;
}
}
When I press back key then the color of bottom navigation not change but my fragment get change. I want to change both at a time. i.e. when I go back then fragment should change with bottom navigation icon.
Here is my current code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private FrameLayout mMainFrame;
Fragment homeFragment = new HomeFragment();
Fragment trendingFragment = new TrendingFragment();
Fragment latestFragment = new LatestFragment();
Fragment inboxFragment= new InboxFragment();
Fragment libraryFragment = new LibraryFragment();
// Adding acion on botom navigation icon basically adding Fragment Action
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.bottom_navigation_home:
setFragment(homeFragment);
return true;
case R.id.bottom_navigation_trending:
setFragment(trendingFragment);
return true;
case R.id.bottom_navigation_latest:
setFragment(latestFragment);
return true;
case R.id.bottom_navigation_inbox:
setFragment(inboxFragment);
return true;
case R.id.bottom_navigation_library:
setFragment(libraryFragment);
return true;
default:
return false;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Decleration Connecting Java To xml
mMainFrame = (FrameLayout) findViewById(R.id.main_container);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.bottom_navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
setFragment(homeFragment); // Start Home Fregment first
}
#Override
public void onBackPressed(){
if (getSupportFragmentManager().getBackStackEntryCount() == 1){
finish();
}
else {
super.onBackPressed();
}
}
//Declear Method
private void setFragment(Fragment fragment) {
// Set fragment in frame layout
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null){ //fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.main_container, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);
ft.addToBackStack(backStateName);
ft.commit();
}
}
}
bottom_nav_color_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/colorPrimary" android:state_checked="true"/>
<item android:color="#color/colorIcon" android:state_checked="false"/>
</selector>
BottomNavigationView in MainActivity.xml
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="#color/colorWhite"
android:clickable="true"
android:focusable="true"
app:itemIconSize="25dp"
app:itemIconTint="#color/bottom_nav_color_selector"
app:itemTextAppearanceActive="#style/BottomNavigationView.Active"
app:itemTextAppearanceInactive="#style/BottomNavigationView"
app:itemTextColor="#color/bottom_nav_color_selector"
app:labelVisibilityMode="labeled"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_navigation" />
hi try this set itemIconTint and itemTextColor a color selector xml of your specific colors
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#color/Black"
app:itemBackground="#color/White"
app:itemIconTint="#color/nav_selector"
app:itemTextColor="#color/nav_selector"
app:menu="#menu/nav_menu" />
here is nav_selector.xml put this file in res->color folder
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/OrangeBrown" android:state_checked="true" />
<item android:color="#color/OrangeBrown" android:state_enabled="true" android:state_pressed="true" />
<item android:color="#color/BlackishGray" />
</selector>
and if you want to click on specific tab you can do that with below code
View view = bottomNavigationView.findViewById(R.id.nav_home);
view.performClick();
Here is ans. to handle bottom navigation perfectly with back pressed and active Navigation button.
public class MainActivity extends AppCompatActivity {
private Fragment homeFragment = new HomeFragment();
private Fragment trendingFragment = new TrendingFragment();
private Fragment latestFragment = new LatestFragment();
private Fragment inboxFragment = new InboxFragment();
private Fragment libraryFragment = new LibraryFragment();
private BottomNavigationView navigation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navigation = findViewById(R.id.bottom_navigation);
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
finish();
} else {
super.onBackPressed();
if (homeFragment.isResumed())
navigation.setSelectedItemId(R.id.bottom_navigation_home);
else if (trendingFragment.isResumed())
navigation.setSelectedItemId(R.id.bottom_navigation_trending);
else if (latestFragment.isResumed())
navigation.setSelectedItemId(R.id.bottom_navigation_latest);
else if (inboxFragment.isResumed())
navigation.setSelectedItemId(R.id.bottom_navigation_inbox);
else if (libraryFragment.isResumed())
navigation.setSelectedItemId(R.id.bottom_navigation_library);
}
}
I've been trying for the last few hours to search around SO, but I couldn't find a solution outside of trying to create a workaround. I'm trying to create a navigation drawer for my app, but to do so I had to end up trying to change my base activity into a fragment. This is the result:
public class ToolReaderActivity extends Fragment implements ToolListFragment.OnToolSelectedListener, CompatActionBarNavListener, OnClickListener {
boolean mIsDualPane = false;
Context c;
ToolListFragment mToolListFragment;
InfoFragment mInfoFragment;
Fragment mContent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
c = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.onepane_with_bar, container, false);
// find our fragments
mToolListFragment = (ToolListFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.toolList);
mInfoFragment = (InfoFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.toolInfo);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.toolList, mToolListFragment).commit();
FragmentTransaction transaction2 = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.toolInfo, mInfoFragment).commit();
mToolListFragment.setContext(c);
mToolListFragment.setOnToolSelectedListener(this);
View infoView = getView().findViewById(R.id.toolInfo);
mIsDualPane = infoView != null && infoView.getVisibility() == View.VISIBLE;
int catIndex = savedInstanceState == null ? 0 : savedInstanceState.getInt("catIndex", 0);
setUpActionBar(mIsDualPane, catIndex);
mToolListFragment.setSelectable(mIsDualPane);
restoreSelection(savedInstanceState);
if (savedInstanceState != null) {
//Restore the fragment's instance
mContent = getActivity().getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
}
return rootView;
}
...
...
...
}
The intended output is a activity with a navigation drawer and thus a fragment. The fragment contains this main activity ToolReaderActivity (named so because it was formerly an activity) which has 1-2 fragments inside of it. It's a ListFragment with a fragment showing the selected items information (as either another fragment if mDualPane is true or launched as a seperate activity otherwise).
I can't figure out a way to get this to work, I've tired changing the order that things are done using onCreate, onCreateView, onActivityCreated, but the error I keep getting is that mToolsListFragment is null at mToolsListFragment.setContext(c);
You can simply create NavigationDrawer with the code below.
public class MainActivity extends AppCompatActivity
{
private NavigationView mNavigationView;
private DrawerLayout mDrawerLayout;
private Toolbar toolbar;
private ActionBarDrawerToggle mDrawerToggle;
private FragmentActivity fragment;
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initDrawerNavigation();
fragmentManager = getFragmentManager();
}
public void initDrawerNavigation()
{
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.app_name);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
{
#Override
public boolean onNavigationItemSelected(MenuItem item)
{
item.setChecked(true);
switch (item.getItemId())
{
case R.id.st_menu:
fragment = new FirstFragment();
break;
case R.id.nd_menu:
fragment = new Second Fragment();
break;
}
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
mDrawerLayout.closeDrawers();
return true;
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open,
R.string.drawer_close)
{
// Called when a drawer has settled in a completely closed state.
public void onDrawerClosed(View view)
{
super.onDrawerClosed(view);
}
// Called when a drawer has settled in a completely open state.
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId())
{
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START); // OPEN DRAWER
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here you have activity_main.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">
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.ActionBar" />
<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:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<include
layout="#layout/your_layout" />
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
app:menu="#menu/navigation_items" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
your_layout can be anything you want. Now you define your FirstFragment class like here:
public class FirstFragment extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
ViewGroup view = (ViewGroup) inflater.inflate(R.layout.target_layout, container, false);
return view;
}
}
You can also refer to this question Navigation Drawer to switch between activities if you want to switch between activities and not fragments. Hope this helps.