java – Switch from one fragment to another by means of a button

Question:

What I'm trying to do is move from one fragment to another when a button is pressed, the code I'm using is:

public class DimensionFragment extends Fragment {

    Button Bmeters,
           Bfeet;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.fragment_dimension, container, false);

        View view = inflater.inflate(R.layout.fragment_dimension, container, false);

            Bmeters = (Button) view.findViewById(R.id.buttonmeters);
        Bmeters.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { 

                Intent Bmeters = new Intent( getActivity() ,Meters.class);
                startActivity(Bmeters);
            }
        });

        Bfeet=(Button)view.findViewById(R.id.buttonfeet);

        return view;

    }

Pero me sale el siguiente error cuando ejecuto

04-26 12:06:04.705
3879-3879/com.example.liantonypozo.calculosmatematicos3
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.liantonypozo.calculosmatematicos3, PID: 3879
android.content.ActivityNotFoundException: Unable to find explicit
activity class
{com.example.liantonypozo.calculosmatematicos3/com.example.liantonypozo.calculosmatematicos3.DimensionFragment};
have you declared this activity in your AndroidManifest.xml?
at
android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
at
android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
at android.app.Activity.startActivityForResult(Activity.java:4225)
at
android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at
android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at
android.support.v4.app.ActivityCompatJB.startActivityForResult(ActivityCompatJB.java:30)
at
android.support.v4.app.ActivityCompat.startActivityForResult(ActivityCompat.java:146)
at
android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:932)
at
android.support.v4.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:1047)
at android.support.v4.app.Fragment.startActivity(Fragment.java:940)
at android.support.v4.app.Fragment.startActivity(Fragment.java:929)
at
com.example.liantonypozo.calculosmatematicos3.Fragmen2$2.onClick(Fragmen2.java:52)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
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:6119)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Answer:

Es mejor trabajar con fragments separados.
por ejemplo crear un propio Layout para el fragment
fragment_meters_layout.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/texto_fragment"
    android:layout_gravity="center"
    android:layout_margin="15dp"
    android:padding="15dp"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textAlignment="center" />

it is just an example.

Then you declare a class that controls it, like you're doing in your other fragment.

FragmentMeter.java

public class FragmentMain extends Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View vista = inflater.inflate(R.layout.fragment_meter_layout, container, false);

    return vista;
}
}

the Layout of your activity should be something like this

activity_main.xml

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">

......

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/contenedor">

</RelativeLayout>

....

If you have your fragments like this, and your activity with a layout that will contain the fragments.

So in your click event you do the following:

  Bmeters = (Button) view.findViewById(R.id.buttonmeters);
    Bmeters.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentMeter fr=new FragmentMeter();
            fr.setArguments(bn);
            getActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.contenedor,fr)
                    .addToBackStack(null)
                    .commit();

        }
    });

from a fragment you can access

getSupportFragmentManager() from your activity with getActivity()

The activity is the one who will change the fragment inside it, that is why the activity of the fragment should be called

Scroll to Top
AllEscort