One fragment for multiple activities

青春壹個敷衍的年華 提交于 2019-12-22 04:36:25

问题


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.


回答1:


How to reuse one Fragment in multiple Activities

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.




回答2:


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




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/39394056/one-fragment-for-multiple-activities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!