1

I have two java classes. One is main activity and other is MyFragment. MyFragment contains a fragment which has a map. I want to display this to my MainActivity. MainActivity Consists of a Navigation Drawer activity. my code for both the classes are:

`public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    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.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();


    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.nav_loc) {

    } else if (id == R.id.nav_set) {

    } else if (id == R.id.nav_info) {

    } else if (id == R.id.nav_abt) {

    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

} `

And MyFragment Code is:

public class MyFragment extends Fragment implements OnMapReadyCallback {
GoogleMap mgoogleMap;
MapView mapView;
View view;
public MyFragment(){

}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);}
@Override
public View onCreateView(LayoutInflater inflater , ViewGroup container, Bundle savedInstanceState){
    view = inflater.inflate(R.layout.content_main,container , false);
    return view;
}

@Override
public void onViewCreated(View view,Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mapView = view.findViewById(R.id.map);
    if(mapView!=null)
    mapView.onCreate(null);
    mapView.onResume();
    mapView.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap){
    MapsInitializer.initialize(getContext());
    mgoogleMap = googleMap;
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    googleMap.addMarker(new MarkerOptions().position(new LatLng(23.2599,77.4126)).title("BHOPAL"));
    CameraPosition bhopal = CameraPosition.builder().target(new LatLng(23.2599,77.4126)).zoom(16).bearing(0).build();
    googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(bhopal));
}

}

How can I combine both the classes so that My main activity shows this fragment. How can I use MyFragment to mainActivity?

2 Answers2

1

Declare a member field in your Activity like

private MyFragment fragment;

initialize it in onCreate():

fragment = MyFragment();

Then attach and show it:

getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, "your_tag").commit()

Where container is the id of the layout that should be replaced with your Fragment's content.

Edit: it seems to me that you used the Android Studio's "Navigation Drawer Activity" template. The correct layout file would be content_main.xml (if you haven't changed that part). You could add your content layout inside the ConstraintLayout that was generated by AS:

 <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

Note that it would be a better approach to use a static factory method for Fragment instantiation, check this question for more background.

Droidman
  • 11,485
  • 17
  • 93
  • 141
0

First, you have to add a container in main_activity.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"> 
<LinearLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
</LinearLayout>
</RelativeLayout>

Then in your MainActivity.java, add this in onCreate (or wherever you want):

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment, "HELLO");
fragmentTransaction.commit();

The first argument passed to add() is the ViewGroup in which the fragment should be placed, specified by resource ID, and the second parameter is the fragment to add.

Belbahar Raouf
  • 760
  • 1
  • 4
  • 17