run map fragment from navigation drawer - android

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()

Related

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.

Attempt to invoke virtual method 'void android.widget.LinearLayout.setVisibility(int)' on a null object reference

I have a navigation drawer activity and I'm trying to replace the mapFragment shown in the background with another fragment. The app always crashes.
Navigation drawer activity:
package georgia.languagelandscape;
//import android.app.FragmentManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
public class NavigationDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, ProfileFragment.OnFragmentInteractionListener, ReplaceFragment.OnFragmentInteractionListener{
MapFragment mapFragment= new MapFragment();
FragmentManager fm = getSupportFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
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);
//me
navigationView.setItemIconTintList(null);
getSupportActionBar().setDisplayShowTitleEnabled(false);
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_replace, mapFragment);
ft.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentTransaction ft = fm.beginTransaction();
ReplaceFragment replaceFragment=new ReplaceFragment();
ft.replace(R.id.content_replace, replaceFragment);
if (id == R.id.nav_feed) {
// Handle the camera action
} else if (id == R.id.nav_my_profile) {
LinearLayout map_layout=(LinearLayout)this.findViewById(R.id.dummyLayout);
map_layout.setVisibility(1);
fm.beginTransaction().hide(fm.findFragmentById(R.id.mapView)).commit();
// fm.beginTransaction().hide(getSupportFragmentManager().findFragmentById(mapFragment)).commit();
//fm.beginTransaction().hide(getSupportFragmentManager().findFragmentById(‌​mapFragment)).c‌​ommit();
//or getSupportFragmentManager().findFragmentById(R.id.mapFragmen‌​t).getView().setVisi‌​bility(View.INVISIBL‌​E);
ProfileFragment profileFragment= new ProfileFragment();
ft.replace(R.id.content_replace, profileFragment);
} else if (id == R.id.nav_my_projects) {
} else if (id == R.id.nav_seetings) {
} else if (id == R.id.nav_log_out) {
}
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
MapFragment:
package georgia.languagelandscape;
//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
//import android.support.v4.app.Fragment;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link MapFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link MapFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MapFragment extends SupportMapFragment implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
#Override
public void onResume() {
super.onResume();
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
}
And Map fragment 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="georgia.languagelandscape.MapFragment">
<LinearLayout
android:id="#+id/dummyLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:visibility="gone" >
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</FrameLayout>
I tried to do it without the linearLayout from the xml file, but it still doesn't work. I cannot use the destroy method or anything else because basically I am not returning a View. How can I hide the map?
Remove this line :
LinearLayout map_layout=(LinearLayout)this.findViewById(R.id.dummyLayout);
map_layout.setVisibility(1);
fm.beginTransaction().hide(fm.findFragmentById(R.id.mapView)).commit();
Check XML files again, If you are using v-16 or v-21 or v-13 or some other configuration files then it will give this NullPointer error.
I had this problem, I changed the files for different configurations and it worked.

Add google maps api v2 in a drawerlayout fragment

I have been trying to insert a map in a drawer layout with a fragment using Android Studio. I have already achieved to display a map, but I can't add markers to it. I wanted to know what am I doing wrong. And is there any other way to add a map to a drawer layout?
Here's my MainActivity:
package com.example.alex.testing_map;
import android.content.Intent;
import android.os.Bundle;
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.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MapsActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(
this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer);
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
Fragment fragment = new MapFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame_content, fragment);
ft.commit();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.add_item:
Intent intent = new Intent(this, AddMail.class);
this.startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()){
case R.id.mapa:
fragment = new MapFragment();
FragmentTransaction ft1 = getSupportFragmentManager().beginTransaction();
ft1.replace(R.id.frame_content, fragment);
ft1.commit();
break;
case R.id.help:
fragment = new Help();
FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
ft2.replace(R.id.frame_content, fragment);
ft2.commit();
break;
case R.id.about:
break;
default:
return true;
}
DrawerLayout drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
My MapFragment:
package com.example.alex.testing_map;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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 Fragment implements OnMapReadyCallback{
private GoogleMap mMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.map_fragment, viewGroup, false);
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setCompassEnabled(false);
mMap.getUiSettings().setIndoorLevelPickerEnabled(false);
mMap.getUiSettings().setMapToolbarEnabled(false);
mMap.getUiSettings().setRotateGesturesEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
LatLng p1 = new LatLng(41.39355, 2.15473);
mMap.addMarker(new MarkerOptions().position(p1));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(p1, 18));
}
}
With this everything runs well, but markers are not displayed. I've tried to add this (and all the variants I have found) to the MapFragment class, but it says "cannot resolve method 'getSupportFragmentManager' ":
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
My xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="513dp"
tools:context="com.example.alex.testing_map.MapsActivity"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
I found a solution!! I've followed the answer given by Boss here: Trying to put a map in a fragment activity
I've only changed a little thing. Instead of adding the fragment in the transaction, I have replaced it (in the MapFragment.java), and then in the onCreate in the MainActivity I've added the fragment instead of replacing it.
In the MainActivity (inside the onCreate):
Fragment fragment = new MapFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.frame_content, fragment);
ft.commit();

fragment text appearing in toolbar

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.

onitemclicklistener does not work after fragment is executed

my problem is that as soon as i call a fragment in my main layout, the fragment is called in the frame, but after that, the onitemclick listener stops working. what is that i missed ?
the main.java
import java.util.Locale;
import android.annotation.TargetApi;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawerMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTitle = mDrawerTitle = getTitle();
mDrawerMenu = getResources().getStringArray(R.array.menu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_view);
// set a custom shadow that overlays the main content when the drawer opens
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.custom_menu_list, mDrawerMenu));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
//Action bar on item click events
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action buttons
switch(item.getItemId()) {
case R.id.menu_icon:
// create intent to perform web search for this planet
Log.d("Hello","Menu clicked");
mDrawerLayout.openDrawer(mDrawerList);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
Log.d("Hello", String.valueOf(position));
//Get the option name and compare
TextView text = (TextView) arg1.findViewById(android.R.id.text1);
String MenuName = text.getText().toString();
Log.d("Click", MenuName);
if(position == 0){
Log.d("Click","Home Clicked");
// update the main content by replacing fragments
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MenuFragment fragment = new MenuFragment();
fragmentTransaction.replace(R.id.drawer_layout, fragment, String.valueOf(position));
fragmentTransaction.commit();
}
else if(position == 1){
Log.d("Click","News Clicked 2");
}
mDrawerLayout.closeDrawer(mDrawerList);
}
}
}
This is the main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"/>
<!-- The navigation drawer -->
<ListView android:id="#+id/list_view"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#000000"/>
</android.support.v4.widget.DrawerLayout>
This is the menugragment which calls the layout.
public class MenuFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.sports, container, false);
}
}
Now, as it is replaced in the frame in main (when the position is 0, the fragment is called),after that if 1 is called, the onitemclicklistener does not work. why is that ?
Thank you
replace
fragmentTransaction.replace(R.id.drawer_layout, fragment, String.valueOf(position));
to
fragmentTransaction.replace(R.id.content_frame, fragment, String.valueOf(position));
You should replace the content_frame not the drawer_layout

Categories

Resources