I have my Events.java and event.xml layout, which has a recycler view & works fine when if I load the Event class directly. It looks like this:
However, if I load the navigation drawer, which then load the event.xml file, then I get the following screens with this error: "No adapter attached; skipping layout".
My issues is that why is the navigation menu not working and the event layout file not loading? As for my code, I think the following might be helpful.
Events.java
#Override
protected void onCreate(Bundle savedInstanceState) {
...
RecyclerView recyclerView = findViewById(R.id.events_rv_list);
EventsAdapter eventsAdapter = new EventsAdapter(this, eList, this);
recyclerView.setAdapter(eventsAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
events.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Events"
android:background="#ffff6c">
<android.support.v7.widget.RecyclerView
android:id="#+id/events_rv_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>
NavigationDrawer.java
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
...
Okay, I've found the solution. The error was that the adapter was not attached to the RecyclerView.
In the first picture, the adapter worked because it was stored in a normal layout file (non fragment) class, so the onCreate was being called from the events.java. Events.java then loaded the layout (events.xml) and also attached the adapters to the RecyclerView like so:
RecyclerView recyclerView = view.findViewById(R.id._events_recyclerview);
ADAPTE_CLASS adapter = new ADAPTE_CLASS(PASS DATA IF NECESSARY);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
Now same thing can be applied in a Fragment where you can add the above code to onCrateView method (with relevant class names & ids). So that's how you set a recyclerview adapter in a fragnent.
Hope that helps.
Related
I want to add a Back button in a toolbar that I created because I deleted the default one to have the material design effect with some tabs, but every time I add the code to make that button appear, Android gives an exception saying this:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.juan.sdfnsdfnskdfnskdfmsfd, PID: 13348
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.support.v4.widget.DrawerLayout.getDrawerLockMode(int)' on a null object reference
at android.support.v7.app.ActionBarDrawerToggle.toggle(ActionBarDrawerToggle.java:284)
at android.support.v7.app.ActionBarDrawerToggle$1.onClick(ActionBarDrawerToggle.java:202)
at android.view.View.performClick(View.java:6308)
at android.view.View$PerformClick.run(View.java:23969)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1557)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
I do not understand what it means with a null object reference if I only write the corresponding code in the toolbar that I created.
This is the toolbar.xml:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/toolbar_morado"
android:id="#+id/toolbar_lista_compras"
android:minHeight="?attr/actionBarSize">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/contador_toolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lista de compras"
android:textSize="18sp"
android:textColor="#ffffff"/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
This is where I implement the toolbar:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:id="#+id/appBarLayoutCalcular">
<include layout="#layout/toolbar"></include>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tablayoutCalcular"
app:tabGravity="fill"
app:tabMode="fixed"
android:background="#color/toolbar_anaranjado"
app:tabTextAppearance="#style/myTabSize"
app:tabIndicatorColor="#5c1be1"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPagerCalcular"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
This is my class:
public class CalculateMaterials extends AppCompatActivity{
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
Toolbar toolbar;
NavigationView navigationView;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
String tabSeleccionado;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calcular_materiales);
toolbar = (Toolbar)findViewById(R.id.toolbar_shopping_list);
toolbar.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.toolbar_anaranjado));
setSupportActionBar(toolbar);
// text for the toolbar
TextView textoToolbar = (TextView)findViewById(R.id.contador_toolbar);
textoToolbar.setText("Calcular los materiales");
// status bar color
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(getApplicationContext(), R.color.statusBar_anaranjado));
}
// adding toolbar back button
// this is where I have the error
if (toolbar != null) {
toolbar.setNavigationIcon(R.drawable.backButton);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
navigationView = (NavigationView)findViewById(R.id.navigationView);
tabLayout = (TabLayout)findViewById(R.id.tablayoutCalcular);
viewPager = (ViewPager)findViewById(R.id.viewPagerCalcular);
// adding the tabs
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new FragmentCalcular(), "Con area");
viewPagerAdapter.addFragments(new FragmentCalcular2(), "Con metros");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
I also try with:
// add back arrow to toolbar
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
That also gives the same error.
So, Can anyone help me with this problem?
Edit
Thanks to everyone who tried to help me with this problem. I finally found the error.
Some time ago, I tried to add a navigationView in all the activities, but I forgot to delete the necessary code in the class, that's why the drawerLayout doesnt appears in the xml.
So, when I delete the drawerLayout variable, everything works!
Try this
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
Try this.
toolbar = (Toolbar) findViewById(R.id.toolbar_editprofile);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false):
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back_arrow));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
It seems like drawerLayout is null. I can't able to find find your "drawer_layout" in XML.
Make sure you are using the same id for the navigation drawer in findViewById(R.id.drawer_layout) and in the layout file.
First thing where is your DrawerLayout ? i cant find it from your question may be you forgot to post it or not created yet.
make sure you have to declare correct ID for DrawerLayout so check drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout); of drawer_layout.xml
Error Line: i have found error in this line may be this is not your answer but should have to correct you
TextView textoToolbar = (TextView)findViewById(R.id.contador_toolbar);
Try This
toolbar = (Toolbar)findViewById(R.id.toolbar_shopping_list);
toolbar.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.toolbar_anaranjado));
setSupportActionBar(toolbar);
// text for the toolbar
TextView textoToolbar = (TextView)toolbar.findViewById(R.id.contador_toolbar);
textoToolbar.setText("Calcular los materiales");
In onCreate method paste this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolBarGig);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
after this you have to override method:-
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
Try this. Hope it will helps you!
First initialize the toolbar bar for back button
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
then call back button method this code is enough to go to previous
activity else you can use intent method inside onBackPressed method to
go back
//method on back button click
#Override
public void onBackPressed() {
super.onBackPressed();
/*OR
Intent forgot_password = new Intent( AddItemActivity.this, HomeActivity.class);
startActivity(forgot_password);
finish();
}*/
back button click functionality
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a fragment layout which is the drawer and looks like this:
fragment_overview.xml
<?xml version="1.0" encoding="utf-8"?>
<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">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffe887" />
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="multipleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
And the java class for that fragment:
OverviewFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_overview, container, false);
mlistOptions = getResources().getStringArray(R.array.list_options);
mDrawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
mDrawerList = (ListView) getActivity().findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(getActivity(),
R.layout.simple_list_item_1, mlistOptions));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
return root;
}
With this code in the resources folder:
<string-array name="list_options">
<item>Ship</item>
<item>Map</item>
<item>Mail</item>
<item>Settings</item>
<item>Logout</item>
</string-array>
And this as a list item:
simple_list_item_1.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"
android:textColor="#android:color/black"
android:textStyle="italic">
However when the setAdapter method runs in the java class it generates this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
What could have actually gotten wrong in that method call? It is a fragment so we need getActivity as the first parameter, the layout file is just a reference to a simple file and the optionslist is just an arraylist from the resources folder.. what can be null?
Thanks in advance!
try this, instead of using getActivity use root were you inflate your layout because your component now in root view.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_overview, null);
mlistOptions = getResources().getStringArray(R.array.list_options);
mDrawerLayout = (DrawerLayout) root.findViewById(R.id.drawer_layout);
mDrawerList = (ListView) root.findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(getActivity(),
R.layout.simple_list_item_1, mlistOptions));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
return root;
}
you should populate your drawer list in your main activity. Put this code in your activity's onCreate method.
Then in your fragment's onCreateView you shouuld inflate another Layout that will be put in your (main activity's) FrameLayout.
Try replacing your
mDrawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
mDrawerList = (ListView) getActivity().findViewById(R.id.left_drawer);
with
mDrawerLayout = (DrawerLayout) root.findViewById(R.id.drawer_layout);
mDrawerList = (ListView) root.findViewById(R.id.left_drawer);
I'm trying to show my fragment in another activity. At first everything was fine but after editing code my fragment don't shows up. This is my main activity content XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="ir.aftabeshafa.shafadoc.MainActivity"
tools:showIn="#layout/app_bar_main">
<fragment
android:id="#+id/headlines_fragment"
android:name="ir.aftabeshafa.shafadoc.CatFrag"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
And fragment class:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.card_front, container, false);
for (int i = 0; i < imgs.size(); i++) {
CatModel catModel = new CatModel();
catModel.txt = cat[i];
catModel.imgid = imgs.get(i);
arrayList.add(catModel);
}
recyclerView = (RecyclerView) inflater.inflate(R.layout.card_front, container, false).findViewById(R.id.recycler);
StaggeredGridLayoutManager gridLayoutManager =
new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setHasFixedSize(true);
catAdapter = new CatAdapter(arrayList);
recyclerView.setAdapter(catAdapter);
return view;
}
Main Activity class:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#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, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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) {
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
When I debugging my app the container in fragment class is null. Why is this happening?
You are assigning recyclverView from a newly inflated layout when you should be working with the layout you already inflated previously and assigned to view.
This means the view you are returning still has an empty recyclerView. To fix this change:
recyclerView = (RecyclerView) inflater.inflate(R.layout.card_front, container, false).findViewById(R.id.recycler);
To:
recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
so that you use the recyclerView associated with the view you are returning.
I found my problem it was findviewbyid in fragment class. I changed this:
recyclerView = (RecyclerView) inflater.inflate(R.layout.card_front, container, false).findViewById(R.id.recycler);
to this:
recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
So I am using the default Navigation Drawer for my Android Application. What I'm trying to do is linking a button to a fragment I created.
In the fragment I created, I am trying to open up Google Maps.
Whenever I click on the button however, I get this crash:
This is the generated error (i have no syntax errors):
E/FragmentManager: No view found for id 0x7f0d0089 (com.example.x.x:id/mapView) for fragment LocationFragment{35b5044 #1 id=0x7f0d0089}
This is the code from the default menu (I try to only put the needed code):
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentManager fm = getFragmentManager();
}
In the same default Navigation drawer, we also have the onNavigationItemSelected(MenuItem item) function, that does an action when you click on the menu item, this is where I make the FragmentManager call my LocationFragment:
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fm = getFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_camara) {
// Handle the camera action
} else if (id == R.id.nav_share) {
fm.beginTransaction().replace(R.id.mapView, new LocationFragment()).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
And here we have the LocationFragment Java class (witht he most important function included):
public class LocationFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflate and return the layout
View v = inflater.inflate(R.layout.location_fragment, container,
false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello
return v;
}
The layout file (xml) of the LocationFragment (called location_fragment.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
I do not understand why I get the error, since I have checked all ID's in all classes for maybe 100 times. I seem be stuck here. Any help would be appreciated
Thanks in advance
Added 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: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_main" android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView android:id="#+id/nav_view"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:layout_gravity="start" android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main" app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
From this , it says: Replace method replaces an existing fragment that was added to a container.
public abstract FragmentTransaction replace (int containerViewId, Fragment fragment)
Where containerViewId is a container. I dont think MapView is a container. So instead of:
fm.beginTransaction().replace(R.id.mapView, new LocationFragment()).commit();
It should be:
fm.beginTransaction().replace(R.id.mapViewContainer, new LocationFragment()).commit();
Where mapViewContainer is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/mapViewContainer">
Hope this help.
I want to make a toolbar inside one of my tabs but nothing works for me. Can this even be done? I currently have a toolbar above my tabs but i need it to appear inside the first tab.
Here's the code (with the toolbar above tabs):
import ...
public class MainActivity extends ActionBarActivity {
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[] = {"Projects", "People", "Files"};
int Numboftabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setViewPager(pager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_primary, menu);
return true;
}
final ArrayList<String> listItems = new ArrayList<String>();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.addButton) {
final TextView noProject = (TextView) findViewById(R.id.NOPROJECT);
final ListAdapter addAdapter = new ArrayAdapter<String>(this,
R.layout.list_item, R.id.listFrame, listItems);
final ListView lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(addAdapter);
noProject.setVisibility(View.GONE);
lv.setVisibility(View.VISIBLE);
listItems.add("New Project");
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent switchToEdit = new Intent(MainActivity.this,
TeamCreate.class);
startActivity(switchToEdit);
}
});
}
return super.onOptionsItemSelected(item);
}
}
First tab:
import ...
public class Tab1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
return v;
}
}
I faced a similar challenge with a non-standard toolbar and tabs and got past it, though frankly the results were odd looking. You can probably get the toolbar to work under the tab using a similar technique, however it may leave your users scratching their heads. Your technique will have 2 toolbars, one holding the TabLayout widget and another one inside the fragment(s) in the ViewPager.
I was using Material Design tabs for the Detail view in my app. It looked fine until I did the 2-pane Master-Detail view for tablets. Then I had an issue with the tabs wanting to be directly under the toolbar, but no obvious way to have the Master & Detail share the toolbar with the tabs only showing up under the Detail portion of the screen.
I got it working by:
Create a "NoActionBar" style in styles.xml, then refer to it in your main layout using "android:theme="#style/AppTheme".
<!-- Turn off normal application bar so we can put our toolbars where we please.
Do this by replacing "Theme.AppCompat.Light.DarkActionBar" with NoActionBar
per http://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/ -->
<style name="AppTheme" parent="MaterialTheme.Base"/>
<style name="MaterialTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="windowNoTitle">true</item>
<!--We will be using the toolbar so no need to show ActionBar-->
<item name="windowActionBar">false</item>
Toss android.support.design.widget.CoordinatorLayout and just use a LinearLayout.
Here is a snippet that has the toolbar containing the tabs only taking up part of the screen real estate rather than the entire width. Note that the toolbar has "app:layout_scrollFlags="scroll|enterAlways":
<FrameLayout android:id="#+id/detail_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="end"
android:layout_weight="2"
tools:name="com.android.bazemom.popularmovies.TabContainerFragment"
>
<!-- second toolbar that will be used for the tabs -->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways"
/>
<android.support.design.widget.TabLayout
android:id="#+id/tabanim_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<!-- Helps handing the Fragments to load for each Tab -->
<android.support.v4.view.ViewPager
android:id="#+id/tabanim_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
Here is what the Master-Detail view looked like on wide tablet. The tabs are circled in green. The toolbar with an action is above the tabs.