One fragment for multiple activities
Asked Answered
G

4

9

We always have heard using multiple fragments with one activity. Is opposite possible? I am curious about this. Can we use same fragment for multiple activities. Please give ONE EXAMPLE.

Grison answered 8/9, 2016 at 14:50 Comment(1)
developer.android.com/guide/components/fragments.html#Design "For example—to continue with the news application example—the application can embed two fragments in Activity A, when running on a tablet-sized device. However, on a handset-sized screen, there's not enough room for both fragments, so Activity A includes only the fragment for the list of articles, and when the user selects an article, it starts Activity B, which includes the second fragment to read the article."Ungotten
T
4

How to reuse one Fragment in multiple Activities

enter image description here

The green background with two buttons is a single fragment that is reused among multiple activities.

1. Make your fragment class and layout

MyFragment.java

import android.support.v4.app.Fragment;

public class MyFragment extends Fragment implements View.OnClickListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View myLayout = inflater.inflate(R.layout.my_fragment_layout, container, false);

        // add click listeners to the buttons in the fragment
        Button buttonOne = myLayout.findViewById(R.id.button_1);
        Button buttonTwo = myLayout.findViewById(R.id.button_2);
        buttonOne.setOnClickListener(this);
        buttonTwo.setOnClickListener(this);

        return myLayout;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_1:
                Toast.makeText(getContext(), "Button One", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button_2:
                Toast.makeText(getContext(), "Button Two", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}

my_fragment_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_green_dark"
    android:orientation="vertical">

    <Button
        android:id="@+id/button_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 1"/>

    <Button
        android:id="@+id/button_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 2"/>
</LinearLayout>

2. Add the fragment to your activities

activity_blue.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_dark"
    android:orientation="vertical">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="goToRedActivityButtonClick"
        android:text="Go to red activity"/>

    <!-- reused fragment -->
    <fragment
        android:id="@+id/my_fragment"
        android:name="com.example.onefragmentmultipleactivities.MyFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>

activity_red.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff3636"
    android:orientation="vertical">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="goToYellowActivityButtonClick"
        android:text="Go to yellow activity"/>

    <!-- reused fragment -->
    <fragment
        android:id="@+id/my_fragment"
        android:name="com.example.onefragmentmultipleactivities.MyFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>

activity_yellow.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f9f478"
    android:orientation="vertical">

    <!-- reused fragment -->
    <fragment
        android:id="@+id/my_fragment"
        android:name="com.example.onefragmentmultipleactivities.MyFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>

Notes

For simplicity we added the fragment directly to the xml. You can also load fragments dynamically in code. See the documentation for help with that.

Timpani answered 21/9, 2017 at 11:35 Comment(2)
How could I access the buttons on the fragment from the activity class?Tica
@Mwas, you could have a public getter method in the fragment. The getter can return a reference to the button. The activity could access this method directly if it needs to initiate the contact. If the fragment needs to send a message to the activity on a button click then you should use a listener interface. See this answer for an example of both types of communication. Probably what you want is the listener. Each activity that includes the fragment will implement the listener interface.Timpani
M
0

Yes, it is possible to have one fragment with multiple activities. But you will need to program the layout with java using LayoutParams and embed them in every fragment instance.

On every activity, you need to call this fragment Create your UI Components in Java, add them to the layout dynamically from Java Class i.e. Your Activities.

I would suggest this approach will not be easy to maintain, if you are not super comfortable with Java exclusively. You will need to forget XML for this approach as nothing will be there in it at all, everything will be done with Java classes only.

Milore answered 8/9, 2016 at 15:42 Comment(2)
Why would you need to do the layout in Java?Grimsby
So that it is completely portable and dynamic. It is will recreate the same fragment everytime at multiple places so you will have to shed out your xml from the beginning. Or else you will need to have a framelayout setup for it and everytime you will need to switch the layoutsMilore
A
0

generic_error_msg_fragment.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/White" >

    <TextView
        android:id="@+id/error_message_textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:textColor="@android:color/darker_gray"
        android:textSize="@dimen/font_size_16sp" />


        <Button
            android:id="@+id/error_button_handler"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
             android:layout_alignParentBottom="true"
            android:layout_gravity="left|center_vertical"
            android:textSize="@dimen/font_size_16sp"
             />

</RelativeLayout>

GenericErrorFragment.Java

public class GenericErrorFragment extends Fragment{


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {


        View genericView = inflater.inflate(R.layout.generic_error_msg_fragment, null);
        TextView errorText = (TextView) genericView.findViewById(R.id.error_message_textview);

        errorText.setText("error msg" );

        Button errorbutton = (Button) genericView.findViewById(R.id.error_button_handler);

        errorbutton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // your logic launch some other activity

            }
        });
        return genericView;
    }

}

you can load this fragment in any activity and can define your custom text for error and button handler

Agueweed answered 8/9, 2016 at 16:15 Comment(0)
M
-1

I will not write whole code but I can give you exact example you are looking for

Think of an application in which a person can register either as admin or as user

Now while working on it you make 3 fragments in admin registration activity asking

1.) personal information

2.) academic information

3.) admin details

Now for user registration activity say you make 2 fragments to get the following information

1.) personal information

2.) user details

here you used personal information fragment 2 times for 2 activities

code for this is child's play main thing is the concept

Mongolia answered 8/9, 2016 at 15:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.