fragment text appearing in toolbar - android

I'm trying to get a sliding drawer set up. I want the text to appear in the main body of the activity, but instead it's appearing inside of the toolbar, and it only says This is fragment 2, regardless of whether I pulled up the fragment that's supposed to say This is fragment 1 or This is fragment 2.
How can I make it pull up the proper fragment, instead of always fragment 2, and how can I make the toolbar opaque, with text appearing under it instead of in it.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
tools:context="me.paxana.alerta.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="8dp"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentTop="true"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_content"
android:layout_alignParentTop="true">
</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.v4.widget.DrawerLayout>
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.drawable.ic_logout_black_48dp, "Log Out"));
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//display icon to open/close slider
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//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) {
if (position == 2) {
ParseUser.logOut();
navigateToLogin();
} else {
//replace fragment
replaceFragment(position);
//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();
}
}
}

I solved one part of this issue, though I'm not certain I used best practices. I added padding to the top of main_content in a size of "?attr/actionBarSize"
But it's still only displaying This is Fragment 2, regardless of which fragment I'm trying to select.

If you want the content below the toolbar, you can wrap toolbar and content in one layout as:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentTop="true"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_content"
android:background="#8000ff00"
>
</RelativeLayout>
</LinearLayout>
Besides, if you are using Android Studio, creating Navigation Drawer Activity through the wizard is the best way to ensure that everything works properly.

Related

Android: Recyclerview inside fragment fetching data from TMDbApi gives error: E/RecyclerView: No adapter attached; skipping layout

I've been struggling with a problem on android. I have an app with a drawer which shows fragments depending on what menu item you click in the drawer.
Here's how my app currently works:
This is the drawer with the menu buttons:
Whenever I click a button, for instance Profile, it will load the correct Fragment:
Now I have this problem with the Recyclerview withing my fragmentview of TV Show
When I click on tv shows I get a white empty layout like this:
And this is what I get in the logcat:
com.example.derwishe.movielist E/RecyclerView: No adapter attached; skipping layout
Here's my code:
Fragment Class:
package com.example.derwishe.movielist;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.derwishe.movielist.Api.OnGetTvShowsCallback;
import com.example.derwishe.movielist.Api.TvShow;
import com.example.derwishe.movielist.Api.TvShowsRepository;
import java.util.List;
public class TvShowFragment extends Fragment {
private TvShowsRepository tvShowsRepository;
private RecyclerView tvShowList;
private ListAdapter adapter;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view =
inflater.inflate(R.layout.fragment_tvshow,container,false);
tvShowsRepository = TvShowsRepository.getInstance();
tvShowList = (RecyclerView)view.findViewById(R.id.showsRecyclerView);
RecyclerView.LayoutManager layoutManager = new
LinearLayoutManager(getActivity());
tvShowList.setLayoutManager(layoutManager);
this.context = context;
tvShowsRepository.getTvShows(new OnGetTvShowsCallback() {
#Override
public void onSuccess(List<TvShow> tvShows) {
adapter = new ListAdapter(tvShows);
tvShowList.setAdapter(adapter);
}
#Override
public void onError() {
Toast.makeText(context, "Please check your internet
connection.", Toast.LENGTH_SHORT).show(); }
});
return view;
}
}
Listadapter class:
package com.example.derwishe.movielist;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.derwishe.movielist.Api.TvShow;
import java.util.List;
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.TvShowHolder> {
private List<TvShow> tvShows;
public ListAdapter(List<TvShow> tvShows){
this.tvShows = tvShows;
}
#NonNull
#Override
public TvShowHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.shows_item,parent,false);
return new TvShowHolder(view);
}
#Override
public void onBindViewHolder(TvShowHolder holder, int i) {
holder.bind(tvShows.get(i));
}
#Override
public int getItemCount() {
return tvShows.size();
}
class TvShowHolder extends RecyclerView.ViewHolder{
TextView showTitle;
public TvShowHolder(View itemView){
super(itemView);
showTitle = itemView.findViewById(R.id.showTitle);
}
public void bind(TvShow tvShow){
showTitle.setText(tvShow.getTitle());
}
}
}
MainActivity class with drawer:
package com.example.derwishe.movielist;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
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.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
//Reference naar navigatieview voor click events
NavigationView navigationView =findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer,toolbar,R.string.navigation_draw_open,R.string.navigation_draw_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//initiele fragment openen bij start
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new MovieFragment()).commit();
navigationView.setCheckedItem(R.id.nav_movies);
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.nav_movies:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new MovieFragment()).commit();
break;
case R.id.nav_tvshows:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new TvShowFragment()).commit();
break;
case R.id.nav_watchlist:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new WatchlistFragment()).commit();
break;
case R.id.nav_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
break;
case R.id.nav_support:
Toast.makeText(this,"Support message activated",Toast.LENGTH_SHORT).show();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
super.onBackPressed();
}
}
}
And finally the layout files:
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"
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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.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"
app:menu="#menu/draw_menu" />
</android.support.v4.widget.DrawerLayout>
fragment_tvshow.xml which holds the recyclerview
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/showsRecyclerView"/>
</RelativeLayout>
And shows_item.xml which represents 1 item in the recyclerviewlist
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="0dp"
android:layout_height="50dp"
android:scaleType="fitCenter"
android:layout_margin="8dp"
android:layout_weight="1"
android:id="#+id/showImage"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/showTitle"
android:text="Show Title"
android:textSize="22sp"
android:layout_weight="3"
android:layout_margin="22dp"/>
</LinearLayout>
I think it's because once your fragment's onCreate is first run, the recyclerView isn't assigned an adapter, it's until after you fetch your data (the tv shows) that you set the adapter to your recyclerView.
One way to fix this would be to have a constructor that doesn't take any arguments for your adapter, and a method inside it that would pass in whatever data the recyclerView will need to display. You'd end up with something like this:
public class ListAdapter {
public ListAdapter() {}
public void submitList(final List<TvShow> tvShows) {
this.tvShows = tvShows;
notifyDataChanged();
}
}

Fragment is not being replaced after click in navigation drawer

I tried every way to solve this problem but still I am not getting whats wrong with this code. Can you help me?
My mainpage activity is as
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
public class MainPage extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
private FragmentTransaction fragmentTransction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main_page);
Toolbar toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mNavigationView=findViewById(R.id.idnav_view);
ActionBar actionBar=getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
mDrawerLayout=findViewById(R.id.iddrawer_layout);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment frag=null;
int itemId=menuItem.getItemId();
if(itemId==R.id.id_nvHome){
frag=new HomeFragment();
}
else if(itemId==R.id.id_nvSearch){
frag=new SearchFragment();
}
Toast.makeText(getApplicationContext(),menuItem.getTitle(),Toast.LENGTH_SHORT).show();
if(frag!=null){
FragmentTransaction transction=getSupportFragmentManager().beginTransaction();
transction.replace(R.id.idcontent_frame,frag);
transction.commit();
mDrawerLayout.closeDrawers();
return true;
}
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
}
and for mypage activity layout is
<?xml version="1.0" encoding="utf-8"?>
<!-- Use DrawerLayout as root container for activity -->
<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/iddrawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- Layout to contain contents of main body of screen (drawer will slide over this) -->
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/idcontent_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar" />
<!-- Container for contents of drawer - use NavigationView to make configuration easier -->
<android.support.design.widget.NavigationView
android:id="#+id/idnav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/drawer_view"
app:headerLayout="#layout/nav_header"/>
</android.support.v4.widget.DrawerLayout>
my homefragment is as
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_home,container,false);
return v;
}
}
and also layout for that is as
<?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"
tools:context=".HomeFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_marginTop="150dp"
android:layout_marginLeft="150dp"
android:textColor="#000000"
android:textSize="30dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
I want to REPLACE FRAGMENT WITH OTHER FRAGMENT WHEN I CLICK ON NAVIGATION DRAWER ITEMS
Can anyone help me?
I can support you giving you my working code for Android 27.1.1:
public class MainActivity extends AppCompatActivity implements
BottomNavigationView.OnNavigationItemSelectedListener {
private int mSelectedId;
/**
* Create Navigation bar and load the main fragment "statistics".
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new FragmentStatistics());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
mSelectedId = navigation.getSelectedItemId();
}
/**
* Checks for any event in the Navigation Bar.
* If the item selected is the same as the actual item
* Do nothing
* Else
* Load new fragment selected.
*/
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
if (mSelectedId != item.getItemId()) {
mSelectedId = item.getItemId();
switch (item.getItemId()) {
case R.id.statistics:
fragment = new FragmentStatistics();
break;
case R.id.shops:
fragment = new FragmentShops();
break;
}
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
}
The rest of your code is exact as mine.

Android Fragment ViewPager Is Recreating Options Menu

I am making an android app which has a navigation drawer with fragments being loaded on navigation items.
One of the fragment is containing two tabs which is loading another two fragments via ViewPager.
Everything is working fine as expectations but the problem comes when I select another navigation item from drawer.
One of the tab has options menu but when I go to another fragment and comes back to the earlier, then options menu gets duplicated.
Class LunchTabsFragment
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.*;
public class LunchTabsFragment extends Fragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_lunch_tabs, container, false);
//Setting tabs layout
TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tabs);
tabLayout.addTab(tabLayout.newTab().setText("Menu"));
tabLayout.addTab(tabLayout.newTab().setText("History"));
//Setting pages to be loaded with fragments
final ViewPager viewPager = (ViewPager) v.findViewById(R.id.pager);
viewPager.setAdapter(new LunchTabsPagerAdapter(getFragmentManager(), tabLayout.getTabCount()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return v;
}
}
Class LunchTabsPagerAdapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class LunchTabsPagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public LunchTabsPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
LunchMenuFragment tab1 = new LunchMenuFragment();
return tab1;
case 1:
LunchHistoryFragment tab2 = new LunchHistoryFragment();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
Class MainActivity
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.design.widget.NavigationView;
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.*;
import android.view.Menu;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
public static final int DRAWER_OPEN = R.string.navigation_drawer_open;
public static final int DRAWER_CLOSE = R.string.navigation_drawer_close;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, DRAWER_OPEN, DRAWER_CLOSE);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
navigationView.getMenu().performIdentifierAction(R.id.nav_lunch, 0);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (item.getItemId()) {
case R.id.nav_lunch:
fragment = new LunchTabsFragment();
break;
case R.id.nav_attendance:
fragment = new AttendanceFragment();
break;
case R.id.nav_account:
fragment = new ProfileFragment();
break;
case R.id.nav_logout:
UserSessionManager.getInstance(getApplicationContext()).logout();
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Class AttendanceFragment
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.*;
public class AttendanceFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_attendance, container, false);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Attendance");
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tabs"/>
</RelativeLayout>
<?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_sliding"
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_sliding"
app:menu="#menu/activity_sliding_drawer" />
</android.support.v4.widget.DrawerLayout>
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.gaditek.life.MenuActivity"
tools:showIn="navigation_view">
<item android:id="#+id/action_search"
android:title="Search"
android:icon="#drawable/ic_search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView" />
Class LunchMenuFragment
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.*;
import android.view.Menu;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class LunchMenuFragment extends Fragment implements View.OnClickListener {
private ArrayList<LunchMenuItem> lunchMenuItemsArray;
private ListView listItemView;
private LunchMenuAdapter adapter;
private String search;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_lunch_menu, container, false);
//Initializing Buttons
Button b = (Button) v.findViewById(R.id.btnReview);
b.setOnClickListener(this);
Button a = (Button) v.findViewById(R.id.btnRefresh);
a.setOnClickListener(this);
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onPrepareOptionsMenu(android.view.Menu menu) {
menu.findItem(R.id.action_search).setVisible(true);
super.onPrepareOptionsMenu(menu);
}
}
Had to use this code in each fragment in the way to the navigation action where I don't need the options bar
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(android.view.Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
}

Navigation drawer not showing fragment

I am trying to display different fragment when user clicks on any item from navigation drawer. I am not able to display fragment. I am not getting any error message. It's just not displaying fragment.
Layout:
<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/drawerlayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_content"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/notes_list"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<!-- The navigation drawer -->
<ListView android:id="#+id/navigationitems"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:background="#android:color/darker_gray"
android:dividerHeight="0dp"
/>
</android.support.v4.widget.DrawerLayout>
MainActivity:
package com.example.note.pankajpc.note;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import io.realm.Case;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;
import io.realm.Sort;
public class MainActivity extends AppCompatActivity {
private ListView mNavigationItem;
private DrawerLayout mDrawerLayout;
private FrameLayout mMainContent;
Intent intent;
String [] mNavigationItemArray;
List <DrawerItem> mDrawerItem = new ArrayList();
private ActionBarDrawerToggle mDrawerToggle;
private RecyclerView mRecyclerView;
private static NoteAdapter mNoteAdapter;
private static Realm mRealm;
private static Context context1;
private RealmResults<NoteModel> mResults;
SearchView mSearchView;
String mSearchString=null;
private ContextMenu contextMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
Realm.init(this);
context1 = this;
// initAlarm();
mRealm = Realm.getDefaultInstance();
//initialize relam database
initUi();
initDrawerItem();
mRecyclerView = (RecyclerView)findViewById(R.id.notes_list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
mNoteAdapter = new NoteAdapter(this,mResults,mRealm);
mRecyclerView.setAdapter(mNoteAdapter);
mNavigationItemArray = getResources().getStringArray(R.array.navigation_list);
mNavigationItem = (ListView)findViewById(R.id.navigationitems);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_navigation);
mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.app_name,R.string.app_name){
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
//setting custom adapter on Navigation Drawer
mNavigationItem.setAdapter(new CustomDrawerAdapter(this,R.layout.custom_navigation_listview_row,mDrawerItem));
//setting onClick Listener on Navigation Drawer
mNavigationItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Fragment fragment = null;
mDrawerLayout.closeDrawers();
switch (mDrawerItem.get(i).getItemName()){
case "Add a Note":
intent = new Intent(MainActivity.this,AddNote.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
break;
case "Settings":
Toast.makeText(MainActivity.this,"test1",Toast.LENGTH_SHORT).show();
Fragment fragment1 = new TestFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.main_content, fragment1);
ft.commit();
break;
}
}
});
}
private void initAlarm() {
Intent i = new Intent(this,AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, i, 0);
AlarmManager am = (AlarmManager)this.getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,200,200,alarmIntent);
}
private void initDrawerItem() {
mDrawerItem.add(new DrawerItem("Notes",R.drawable.ic_notes));
mDrawerItem.add(new DrawerItem("Add a Note",R.drawable.ic_add));
mDrawerItem.add(new DrawerItem("Search",R.drawable.ic_search));
mDrawerItem.add(new DrawerItem("Trash",R.drawable.ic_trash));
mDrawerItem.add(new DrawerItem("Settings",R.drawable.ic_settings));
}
private void initUi() {
mResults = mRealm.where(NoteModel.class).findAllSortedAsync("mNoteDateTime");
}
protected void onStart() {
super.onStart();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
mResults.addChangeListener(new RealmChangeListener<RealmResults<NoteModel>>() {
#Override
public void onChange(RealmResults<NoteModel> element) {
mNoteAdapter.update(mResults);
}
});
}
#Override
//This override displays the items when action bar up button click
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
//handling the menu clicks on menu.xml
switch (id){
case R.id.actionAdd:
startActivity((new Intent(context1,AddNote.class)).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP));
break;
case R.id.dateCreated:
mResults = mRealm.where(NoteModel.class).findAllSorted("mNoteDateTime");
mNoteAdapter.update(mResults);
break;
case R.id.alphabetically:
mResults = mRealm.where(NoteModel.class).findAllSorted("mNoteTitle");
mNoteAdapter.update(mResults);
break;
case R.id.priority:
mResults = mRealm.where(NoteModel.class).findAllSorted("mNotePriority", Sort.DESCENDING);
mNoteAdapter.update(mResults);
break;
}
return true;
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
mSearchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
String query = newText.toLowerCase();
mResults = mRealm.where(NoteModel.class).contains("mNoteTitle", query, Case.INSENSITIVE).findAllSorted("mNoteDateTime");
mNoteAdapter.update(mResults);
return false;
}
});
return true;
}
#Override
protected void onStop() {
super.onStop();
resetSearchView();
}
#Override
public void onBackPressed() {
super.onBackPressed();
resetSearchView();
}
private void resetSearchView() {
mSearchView.clearFocus();
mSearchView.setQuery("", false);
mSearchView.setFocusable(false);
mSearchView.onActionViewCollapsed();
}
}
Fragment:
package com.example.note.pankajpc.note;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Pankaj PC on 01-08-2017.
*/
public class TestFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.add_note,container,false);
}
}
You can't use a Linearlayout to store your fragments, its needs to be a Framelayout where you need to add the fragments
This is how I always setup my Navigation Drawer:
<?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">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
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.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/appbar_layout" />
</RelativeLayout>
<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_main_drawer" />
</android.support.v4.widget.DrawerLayout>

run map fragment from navigation drawer

i have been using the navigation drawer and in case 1 i would like to run a google maps API inside a fragment.
but i get the following error:
'replace(int, android.app.Fragment)' in 'android.app.FragmentTransaction' cannot be applied to '(int, com.example.matant.test.MapFragment)'
this is the mainactivity:
package com.example.matant.test;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
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.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ActionBarDrawerToggle actbartoggle;
private android.support.v7.app.ActionBar actionbar;
private DrawerLayout drawer;
private ListView navlist;
private FragmentTransaction frmt;
private FragmentManager frm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer = (DrawerLayout)findViewById(R.id.drawer);
navlist = (ListView)findViewById(R.id.navlist);
ArrayList<String> navArr = new ArrayList<String>();
navArr.add("Home");
navArr.add("Playing List");
navArr.add("Manage List");
navArr.add("Logout");
navlist.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,navArr);
navlist.setAdapter(adapter);
navlist.setOnItemClickListener(this);
actbartoggle = new ActionBarDrawerToggle(this,drawer,R.string.opendrawer,R.string.closedrawer);
drawer.setDrawerListener(actbartoggle);
actionbar = getSupportActionBar();
actionbar.setDisplayShowHomeEnabled(true);
actionbar.setDisplayHomeAsUpEnabled(true);
frm = getFragmentManager();
loadDefFrag(0);
}
private void loadDefFrag(int i){
navlist.setItemChecked(i,true);
if(i==1){
MapFragment mapf = new MapFragment();
frmt = frm.beginTransaction();
frmt.replace(R.id.fragmentholder, mapf);
frmt.commit();
}else if (i==2){
Fragment2 fr2 = new Fragment2();
frmt = frm.beginTransaction();
frmt.replace(R.id.fragmentholder, fr2);
frmt.commit();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actbartoggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}else if (id == android.R.id.home){
if(drawer.isDrawerOpen(navlist)){
drawer.closeDrawer(navlist);
}else{
drawer.openDrawer(navlist);
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
break;
case 1:
loadDefFrag(position);
break;
case 2:
loadDefFrag(position);
break;
case 3:
break;
}
drawer.closeDrawer(navlist);
}
}
here you can see the mapactivity:
package com.example.matant.test;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.example.matant.test.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapFragment extends FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
// Add a marker in Sydney, Australia, and move the camera.
LatLng sydney = new LatLng(-34, 151);
map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
main layout:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentholder">
</FrameLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/navlist"
android:background="#dedede"
android:layout_gravity="start">
</ListView>
</android.support.v4.widget.DrawerLayout>
map layout:
<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.example.matant.test.MapFragment">
<!-- TODO: Update blank fragment layout -->
<fragment 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/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
</FrameLayout>
You are trying to replace an Activity using FragmentManager. Only a Fragment can be used here.
Either start you MapFragment using startActivity() or extend MapFragment from a Fragment like this
public class MapFragment extends Fragment implements OnMapReadyCallback {
If you follow the second approach you will have to change few other lines in code too where you need context using getActivity()

Categories

Resources