2

Im working on a small google maps app that lets users find places close to them, I want to add functionality that lets the user add a place to a list of favourites, So far ive created classes that may do the functionality.

My main activity is my home page which opens other activities, code below:

 import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends AppCompatActivity {

    ImageButton btnNearBy;
    ImageButton btnFavourites;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnNearBy = (ImageButton) findViewById(R.id.btnNearby);
        btnNearBy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mapIntent = new Intent(getBaseContext(), MapsActivity.class);
                startActivity(mapIntent);
            }
        });

        btnFavourites = (ImageButton) findViewById(R.id.btnFavourites);
        btnFavourites.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fragmentManager = MainActivity.this.getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                FavouriteListFragment fragment = new FavouriteListFragment();
                fragmentTransaction.add(R.id.fragment_container, fragment); //ERROR ON THIS LINE
                fragmentTransaction.commit();
            }
        });

    }
}

Ive created a button that should open up the fragment that holds the list of favourites ,My fragment is declared like this: public class FavouriteListFragment extends Fragment { ... }

Im a little unsure how to open the fragment from the MainActivity when clicking a button. Any ideas? Thanks!

T91
  • 135
  • 1
  • 2
  • 9

2 Answers2

3

Since you are using android.support.v4.app.Fragment and there has been a lot of confusion in importing correct version. Try like this:

android.support.v4.app.FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

FavouriteListFragment fragment = new FavouriteListFragment();

fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

Where fragment_container is FrameLayout inside activity_main.

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

Reference

Rohit Arya
  • 6,751
  • 1
  • 26
  • 40
  • I don't have anything with the id of fragment container. Where would I create that? – T91 Apr 12 '16 at 20:22
  • in `activity_main` it should be a `FrameLayout`. – Rohit Arya Apr 12 '16 at 20:28
  • It says `cannot resolve method add` for the `fragmentTransaction.add(R.id.fragment_container, fragment);` line – T91 Apr 12 '16 at 21:00
  • Which `FragmentManager` are you using? try switching it. – Rohit Arya Apr 12 '16 at 21:02
  • @T91, look at my updated answer. I have specifically added which fragmentManager to use. – Rohit Arya Apr 12 '16 at 21:04
  • I first tried the `getFragmentManager()` one and that gave the cannot resolve method. the `getSupportFragmentManager()` says that it found V4 support library. - I edited my original post to show the updated code – T91 Apr 12 '16 at 21:04
  • You have added `public class FavouriteListFragment extends Fragment`, so which fragment is this? `android.app.Fragment` (use `getFragmentManager()`) or `android.support.v4.app.Fragment` (use `getSupportFragmentManager()`) – Rohit Arya Apr 12 '16 at 21:07
  • `FavouriteListFragment` is the fragment that i want to open when clicking on the button – T91 Apr 12 '16 at 21:10
  • @T91 I know that. but it extends `Fragment` so where this fragment has been imported from? `android.support.v4.app.Fragment` OR `android.app.Fragment` – Rohit Arya Apr 12 '16 at 21:13
  • oh sorry my mistake `import android.support.v4.app.Fragment;` – T91 Apr 12 '16 at 21:14
3

There are two ways of displaying fragments:

1- First you need to define a fragment container in your code like the following:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

     <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="do something" 
        android:onClick="openFragment" />
     <FrameLayout
         android:id="@+id/fragment_container"
         android:layout_height="wrap_content"
         android:layout_width="match_content" />
</LinearLayout>

and then you need to create a function called openFragment in your activity and use the following code in openFragment:

getSupportFragmentManager().beginTransaction().add(R.id_fragment_container,new FavouriteListFragment()).commit();

2- You can define the fragment in your activity xml file like:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/my_fragment"
    android:name="com.example.android.something.FavouriteListFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.android.something.FavouriteListFragment"
    tools:layout="@android:layout/fragment_layout" />

The first one is called dynamic fragment creation and the second one is called static. You have more freedom with the first one but if your fragment doesn't change throughout the activity it is simpler to use the second one

Pooya
  • 6,083
  • 3
  • 23
  • 43
  • Thank you for the answer. Would the fragment replace the main activity as I would not want to see that when opening the list. – T91 Apr 12 '16 at 20:42
  • @T91 fragment will never replace your activity but takes part in a view inside an activity. If the layout you want the fragment to occupy is the parent view then yes it occupies your whole view. but if your layout has for example 4 views, you can just use one of the views for fragment and the rest remains for your activity main layout – Pooya Apr 12 '16 at 20:44
  • @T91 if you want to understand the behavior better, I suggest you run some tests on different layouts to see how it works – Pooya Apr 12 '16 at 20:47
  • Ah okay so in this case the fragment will take place inside the main activity? – T91 Apr 12 '16 at 20:52
  • Again thank you for the reply, but my original post was how would i launch the fragment when clicking on a button – T91 Apr 12 '16 at 20:58
  • @T91 I updated my post see the first example. you'll get the idea what to do – Pooya Apr 12 '16 at 21:06
  • I followed that post and created a method as follows: `public void openFragment(){ getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,new FavouriteListFragment()).comit(); }` It says `cannot resolve method commit` – T91 Apr 12 '16 at 21:09
  • @T91: it is commit not comit, my mistake – Pooya Apr 12 '16 at 21:10
  • Ah yes that worked however, when clicking the button the app crashed and i was shown `java.lang.IllegalStateException: Could not find method openFragment(View)` – T91 Apr 12 '16 at 21:13
  • openFragment which you have defined should look like: public void openFragment(View view) – Pooya Apr 12 '16 at 21:14
  • Oh yes that seems to have worked, For some reason when i open the fragment im able to see the buttons from the home page. – T91 Apr 12 '16 at 21:16
  • yes you can since you are just using a single part of the layout for your fragment not the whole layout – Pooya Apr 12 '16 at 21:18
  • Oh never mind, i moved the XML code for the frame underneath the button code and it seems to have worked.But is there a way to go back to the home page from this fragment? – T91 Apr 12 '16 at 21:19
  • @T91 congratulations then. If this solved your problem then please accept it so the question can be closed – Pooya Apr 12 '16 at 21:20
  • @Pooya if I have created a fragment dynamically, how do I close it exactly? I tried using `getActivity().getSupportFragmentManager().popBackstack()` with the combination of this `getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit()` but nothing happens. – G. Rann Jan 28 '19 at 10:02