Fragment

Fragment 可以作为一个轻量级的Activity使用。和Activity一样,它有自己的逻辑(Fragment.java)和视图(fragment.xml)。

  1. 创建 MainActivity.javaactivity_main.xml
  2. 创建 FirstFragment.javafragment_first.xml
  3. 创建 SecondFragment.javafragment_second.xml

MainActivity

MainActivityonCreate方法中加载 FirstFragment, 使用getSupportFragmentManager() .beginTransaction() .add(R.id.container, new FirstFragment()) .commit()

package com.s3abiscuit.android.testfragment;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
/*
* 两个Activity
* MainActivity包含FirstFragment和SecondFragment
* TabActivity包含Image1Fragmen,Image2Fragment和Image3Fragment
 */
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.container, new FirstFragment())
                .commit();
    }
}

activity_main.xml作为fragment的容器 container

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.s3abiscuit.android.testfragment.MainActivity">

</FrameLayout>

FirstFragment

FirstFragment.java定义一个Button跳转到SecondFragmnet,使用getFragmentManager() .beginTransaction() .addToBackStack(null) .replace(R.id.container, new SecondFragment()) .commit()

package com.s3abiscuit.android.testfragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class FirstFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public FirstFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FirstFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FirstFragment newInstance(String param1, String param2) {
        FirstFragment fragment = new FirstFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        System.out.println("FirstFragment_onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("FirstFragment_onCreate");
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        System.out.println("FirstFragment_onCreateView");
        View root = inflater.inflate(R.layout.fragment_first, container, false);
        root.findViewById(R.id.btn_goto_secondfragment).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getFragmentManager()
                        .beginTransaction()
                        .addToBackStack(null)
                        .replace(R.id.container, new SecondFragment())
                        .commit();
            }
        });

        root.findViewById(R.id.btn_goto_tabActivity).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), TabActivity.class));
            }
        });
        return root;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        System.out.println("FirstFragment_onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println("FirstFragment_onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("FirstFragment_onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        System.out.println("FirstFragment_onPause");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        System.out.println("FirstFragment_onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("FirstFragment_onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        System.out.println("FirstFragment_onDetach");
    }
}

fragment_first.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是firstFragment"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳转到secondFragment"
        android:id="@+id/btn_goto_secondfragment"
        android:textAllCaps="false"/>

</LinearLayout>

SecondFragment

SecondFragment.java 定义Button返回到FirstFragment,使用getFragmentManager().popBackStack()

package com.s3abiscuit.android.testfragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class SecondFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public SecondFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SecondFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SecondFragment newInstance(String param1, String param2) {
        SecondFragment fragment = new SecondFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        System.out.println("SecondFragment_onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("SecondFragment_onCreate");
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        System.out.println("SecondFragment_onCreateView");
        View root = inflater.inflate(R.layout.fragment_second, container, false);
        root.findViewById(R.id.btn_goto_firstfragment).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getFragmentManager().popBackStack();
            }
        });
        return root;
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println("SecondFragment_onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("SecondFragment_onResume");
    }


    @Override
    public void onPause() {
        super.onPause();
        System.out.println("SecondFragment_onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println("SecondFragment_onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        System.out.println("SecondFragment_onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("SecondFragment_onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        System.out.println("SecondFragment_onDetach");
    }
}

fragment_second.xml

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

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是secondFragment"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn_goto_firstfragment"
        android:text="跳转到firstFragment"/>

</LinearLayout>
posted @ 2017-10-02 17:27  s3abiscuit  阅读(130)  评论(0编辑  收藏  举报