-2

I am try to separate activity_main.xml, so I decided to use fragments,
I want to know how do I use fragment's XML in MainActivity?

For example in the MainActivity:

button = (Button) findViewById(R.id.fragment's button) 

main.xml :

    <FrameLayout
      android:id="@+id/switch_fragment
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />

FragmentActivity.java:

    private FragmentManager manager = getFragmentManager();
    private fragment1 fragment1;
    private fragment2 fragment2;

    public void onCreate(Bundle savedInstanceState){
     ...
     ...
     fragment1 = new fragment1();
     fragment2 = new fragment2();
     FragmentTransaction ft = manager.beginTransaction();
     ft.add(R.id.switch_fragment, fragment1, "tag1");
     ft.add(R.id.switch_fragment, fragment2, "tag2");
     ft.commit();
     ...
     ...
     init();
     ...
     }

    private void init(){
     // use fragment1's xml
     }
leona lin
  • 11
  • 1
  • 4
  • 1
    Please Read about fragments and Activities first https://developer.android.com/guide/components/activities/index.html, https://developer.android.com/guide/components/fragments.html – Raghavendra Aug 29 '17 at 07:45

2 Answers2

0

Read about fragments in official documentation

https://developer.android.com/guide/components/fragments.html

and read/watch about here:

https://www.youtube.com/watch?v=yOBQHf5nM2I

How do I add a Fragment to an Activity with a programmatically created content view

Community
  • 1
  • 1
chebad
  • 919
  • 1
  • 13
  • 29
0

You can create an interface in fragment class and implement it in your MainActivity class.

    public class MyFragment extends Fragment {
    private onFragmentInteractionListener mListener;

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

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    public interface OnFragmentInteractionListener {
        void onHomepageFragmentInteraction(View view);
    }
    }

And write the below code in your MainActivity.

public class MainActivity extends AppCompatActivity implements 
MyFragment.OnFragmentInteractionListener {
    @Override
    public void onHomepageFragmentInteraction(View view) {
        button = (Button) view.findViewById(R.id.fragment's button)
    }
}
Tavinder Singh
  • 380
  • 1
  • 7
  • 17