如何在MainActivity中获得片段?

时间:2017-08-29 07:43:48

标签: android android-fragments

我尝试将activity_main.xml分开,所以我决定使用片段,
我想知道如何在MainActivity中使用片段的XML?

例如,在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
     }

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

您可以在片段类中创建一个接口,并在MainActivity类中实现它。

    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);
    }
    }

并在MainActivity中编写以下代码。

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