组件 -- Fragment -- 2

八、通信方式

Fragment与Activity通信通常存在三种情形:Activity操作内嵌的Fragment,Fragment操作宿主Activity,Fragment操作同属Activity中的其他Fragment。

由于Activity持有所有内嵌的Fragment对象实例(创建实例时保存的Fragment对象,或者通过FragmentManager类提供的findFragmentById()和findFragmentByTag()方法也能获取到Fragment对象),所以可以直接操作Fragment;Fragment通过getActivity()方法可以获取到宿主Activity对象(强制转换类型即可),进而可以操作宿主Activity;获取到宿主Activity对象的Fragment便可以操作其他Fragment对象。

虽然上述操作已经能够解决Activity与Fragment的通信问题,但会造成代码逻辑紊乱的结果,极度不符合编程思想:高内聚,低耦合。Fragment做好自己的事情即可,所有涉及到Fragment之间的控制显示等操作,都应交由宿主Activity来统一管理。我们推荐使用对外开放接口的形式将Fragment的一些对外操作传递给宿主Activity。

//fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is one fragment layout"/>
</LinearLayout>

//OneFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class OneFragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "OneFragment";
    private IOneFragmentClickListener clickListener;

    public interface IOneFragmentClickListener { //定义监听器接口
        void onOneFragmentClick();
    }

    public void setClickListener(IOneFragmentClickListener clickListener) { //设置监听器
        this.clickListener = clickListener;
    }

    public static OneFragment newInstance(int args){
        Log.d(TAG, "zwm, newInstance, args: " + args);
        OneFragment oneFragment = new OneFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("someArgs", args);
        oneFragment.setArguments(bundle);
        return oneFragment;
    }

    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
        Log.d(TAG, "zwm, onInflate");
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "zwm, onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "zwm, onCreate");
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        int args = -1;
        if(bundle != null) {
            args = bundle.getInt("someArgs");
        }
        Log.d(TAG, "zwm, onCreate, args: " + args);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onCreateView");
        View contentView = inflater.inflate(R.layout.fragment_main, null);
        contentView.findViewById(R.id.textview).setOnClickListener(this);
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onViewCreated");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onActivityCreated");
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "zwm, onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "zwm, onDetach");
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Log.d(TAG, "zwm, onCreateOptionsMenu");
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        Log.d(TAG, "zwm, onPrepareOptionsMenu");
    }

    @Override
    public void onClick(View v) {
        Log.d(TAG, "zwm, onClick");
        if(clickListener != null) {
            clickListener.onOneFragmentClick(); //调用监听器方法
        }
    }
}

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
    
//MainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity implements OneFragment.IOneFragmentClickListener { //实现监听接口
    private static final String TAG = "MainActivity";
    private OneFragment mOneFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "zwm, onCreate");

        mOneFragment = OneFragment.newInstance(99);
        mOneFragment.setClickListener(this); //设置监听器
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.fragment_container, mOneFragment);
        ft.commit();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "zwm, onNewIntent: " + intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    public void onOneFragmentClick() { //覆写监听方法
        Log.d(TAG, "zwm, onOneFragmentClick");
    }
}

//输出log
2020-01-19 14:25:47.922 27409-27409/com.example.sourcecodetest D/MyApplication: zwm, onCreate
2020-01-19 14:25:48.214 27409-27409/com.example.sourcecodetest D/MainActivity: zwm, onCreate
2020-01-19 14:25:48.218 27409-27409/com.example.sourcecodetest D/OneFragment: zwm, newInstance, args: 99
2020-01-19 14:25:48.326 27409-27409/com.example.sourcecodetest D/OneFragment: zwm, onAttach
2020-01-19 14:25:48.326 27409-27409/com.example.sourcecodetest D/OneFragment: zwm, onCreate
2020-01-19 14:25:48.326 27409-27409/com.example.sourcecodetest D/OneFragment: zwm, onCreate, args: 99
2020-01-19 14:25:48.327 27409-27409/com.example.sourcecodetest D/OneFragment: zwm, onCreateView
2020-01-19 14:25:48.335 27409-27409/com.example.sourcecodetest D/OneFragment: zwm, onViewCreated
2020-01-19 14:25:48.335 27409-27409/com.example.sourcecodetest D/OneFragment: zwm, onActivityCreated
2020-01-19 14:25:48.335 27409-27409/com.example.sourcecodetest D/OneFragment: zwm, onStart
2020-01-19 14:25:48.337 27409-27409/com.example.sourcecodetest D/MainActivity: zwm, onStart
2020-01-19 14:25:48.354 27409-27409/com.example.sourcecodetest D/MainActivity: zwm, onResume
2020-01-19 14:25:48.354 27409-27409/com.example.sourcecodetest D/OneFragment: zwm, onResume
2020-01-19 14:25:49.080 27409-27409/com.example.sourcecodetest D/OneFragment: zwm, onCreateOptionsMenu
2020-01-19 14:25:49.080 27409-27409/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 14:25:49.083 27409-27409/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 14:25:51.366 27409-27409/com.example.sourcecodetest D/OneFragment: zwm, onClick
2020-01-19 14:25:51.367 27409-27409/com.example.sourcecodetest D/MainActivity: zwm, onOneFragmentClick

九、getActivity()引用问题

使用中经常会在Fragment中通过getActivity()获取到宿主Activity对象,但稍有不慎便会引发下面这两个问题:

  • 1.Activity的实例销毁问题
    Fragment中存在类似网络请求之类的异步耗时任务,当该任务执行完毕回调Fragment的方法并用到宿主Activity对象时,很有可能宿主Activity对象已经销毁,从而引发NullPointException等异常。所以,异步回调时需要注意添加空值等判断(例如:fragment.isAdd(),getActivity() != null等),或者在Fragment创建实例时就通过getActivity().getApplicationContext()方法保存整个应用的上下文对象,再来使用。
  • 2.内存泄漏问题
    如果Fragment持有宿主Activity的引用,会导致宿主Activity无法回收,造成内存泄漏。所以,如果可以的话,尽量不要在Fragment中持有宿主Activity的引用。

为了解决Context上下文引用的问题,Fragment提供了一个onAttach(context)方法,在此方法中我们可以获取到Context对象,如:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.context = context;
}

十、Fragment重叠问题

当Activity被异常销毁发生重建时,会重新执行onCreate()方法,并再次执行Fragment的创建和显示等操作,而之前已经存在的Fragment实例也会销毁再次创建,这就与Activity中onCreate()方法里面第二次创建的Fragment同时显示从而发生UI重叠的问题。为解决这个问题需要在Activity中创建Fragment实例时添加一个判断:

//Activity#onCreate:
if (savedInstanceState == null) {
    oneFragment = OneFragment.newInstance();
    ft.add(R.id.fl_content, oneFragment, "OneFragment");
    ft.commit();
}

十一、onActivityResult()

Fragment类提供有startActivityForResult()方法用于Activity间的页面跳转和数据回传,其实内部也是调用Activity的对应方法。但是在页面返回时需要注意Fragment没有提供setResult()方法,可以通过宿主Activity实现。

例如,在ActivityA中的FragmentA里面调用startActivityForResult()跳转至ActivityB中,并在ActivityB中的FragmentB里面返回到ActivityA,代码如下:

//fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is one fragment layout"/>
</LinearLayout>

//OneFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class OneFragment extends Fragment {
    private static final String TAG = "OneFragment";

    public static OneFragment newInstance(int args){
        Log.d(TAG, "zwm, newInstance, args: " + args);
        OneFragment oneFragment = new OneFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("someArgs", args);
        oneFragment.setArguments(bundle);
        return oneFragment;
    }

    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
        Log.d(TAG, "zwm, onInflate");
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "zwm, onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "zwm, onCreate");
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        int args = -1;
        if(bundle != null) {
            args = bundle.getInt("someArgs");
        }
        Log.d(TAG, "zwm, onCreate, args: " + args);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onCreateView");
        View contentView = inflater.inflate(R.layout.fragment_main, null);
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "zwm, onViewCreated");
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "zwm, onActivityCreated");

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "zwm, test startActivityForResult ");
                Intent intent = new Intent(getActivity(), SubActivity.class);
                startActivityForResult(intent, 10);
            }
        }, 5000);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "zwm, onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "zwm, onDetach");
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Log.d(TAG, "zwm, onCreateOptionsMenu");
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        Log.d(TAG, "zwm, onPrepareOptionsMenu");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "zwm, onActivityResult, extra: " + data.getStringExtra("extra"));
    }
}

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
    
//MainActivity
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private OneFragment mOneFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "zwm, onCreate");

        mOneFragment = OneFragment.newInstance(99);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.fragment_container, mOneFragment);
        ft.commit();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "zwm, onNewIntent: " + intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "zwm, onActivityResult, extra: " + data.getStringExtra("extra"));
    }
}

//fragment_sub.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is sub fragment layout"/>
</LinearLayout>

//SubFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class SubFragment extends Fragment {
    private static final String TAG = "SubFragment";

    public static SubFragment newInstance(int args){
        Log.d(TAG, "zwm, newInstance, args: " + args);
        SubFragment subFragment = new SubFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("someArgs", args);
        subFragment.setArguments(bundle);
        return subFragment;
    }

    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
        Log.d(TAG, "zwm, onInflate");
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "zwm, onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "zwm, onCreate");
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        int args = -1;
        if(bundle != null) {
            args = bundle.getInt("someArgs");
        }
        Log.d(TAG, "zwm, onCreate, args: " + args);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onCreateView");
        View contentView = inflater.inflate(R.layout.fragment_sub, null);
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onViewCreated");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onActivityCreated");
        super.onActivityCreated(savedInstanceState);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "zwm, test setResult");
                Intent intent = new Intent();
                intent.putExtra("extra", "This is setResult");
                getActivity().setResult(Activity.RESULT_OK, intent);
                getActivity().finish();
            }
        }, 5000);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "zwm, onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "zwm, onDetach");
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Log.d(TAG, "zwm, onCreateOptionsMenu");
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        Log.d(TAG, "zwm, onPrepareOptionsMenu");
    }
}

//SubActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class SubActivity extends AppCompatActivity {
    private static final String TAG = "SubActivity";
    private SubFragment mSubFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "zwm, onCreate");

        mSubFragment = SubFragment.newInstance(9999);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.fragment_container, mSubFragment);
        ft.commit();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "zwm, onNewIntent: " + intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }
}

//输出log
2020-01-19 15:11:32.694 7644-7644/com.example.sourcecodetest D/MyApplication: zwm, onCreate
2020-01-19 15:11:32.935 7644-7644/com.example.sourcecodetest D/MainActivity: zwm, onCreate
2020-01-19 15:11:32.938 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, newInstance, args: 99
2020-01-19 15:11:32.951 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onAttach
2020-01-19 15:11:32.951 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onCreate
2020-01-19 15:11:32.951 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onCreate, args: 99
2020-01-19 15:11:32.952 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onCreateView
2020-01-19 15:11:32.959 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onViewCreated
2020-01-19 15:11:32.959 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onActivityCreated
2020-01-19 15:11:32.960 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onStart
2020-01-19 15:11:32.961 7644-7644/com.example.sourcecodetest D/MainActivity: zwm, onStart
2020-01-19 15:11:32.964 7644-7644/com.example.sourcecodetest D/MainActivity: zwm, onResume
2020-01-19 15:11:32.965 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onResume
2020-01-19 15:11:33.088 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onCreateOptionsMenu
2020-01-19 15:11:33.088 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 15:11:33.090 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 15:11:37.967 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, test startActivityForResult 
2020-01-19 15:11:38.023 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onPause
2020-01-19 15:11:38.023 7644-7644/com.example.sourcecodetest D/MainActivity: zwm, onPause
2020-01-19 15:11:38.120 7644-7644/com.example.sourcecodetest D/SubActivity: zwm, onCreate
2020-01-19 15:11:38.121 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, newInstance, args: 9999
2020-01-19 15:11:38.126 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onAttach
2020-01-19 15:11:38.126 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onCreate
2020-01-19 15:11:38.126 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onCreate, args: 9999
2020-01-19 15:11:38.127 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onCreateView
2020-01-19 15:11:38.131 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onViewCreated
2020-01-19 15:11:38.131 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onActivityCreated
2020-01-19 15:11:38.132 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onStart
2020-01-19 15:11:38.132 7644-7644/com.example.sourcecodetest D/SubActivity: zwm, onStart
2020-01-19 15:11:38.134 7644-7644/com.example.sourcecodetest D/SubActivity: zwm, onResume
2020-01-19 15:11:38.135 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onResume
2020-01-19 15:11:38.206 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onCreateOptionsMenu
2020-01-19 15:11:38.206 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onPrepareOptionsMenu
2020-01-19 15:11:38.206 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onPrepareOptionsMenu
2020-01-19 15:11:38.624 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onStop
2020-01-19 15:11:38.625 7644-7644/com.example.sourcecodetest D/MainActivity: zwm, onStop
2020-01-19 15:11:43.138 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, test setResult
2020-01-19 15:11:43.174 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onPause
2020-01-19 15:11:43.175 7644-7644/com.example.sourcecodetest D/SubActivity: zwm, onPause
2020-01-19 15:11:43.238 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onActivityResult, extra: This is setResult
2020-01-19 15:11:43.238 7644-7644/com.example.sourcecodetest D/MainActivity: zwm, onActivityResult, extra: This is setResult
2020-01-19 15:11:43.252 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onStart
2020-01-19 15:11:43.253 7644-7644/com.example.sourcecodetest D/MainActivity: zwm, onStart
2020-01-19 15:11:43.263 7644-7644/com.example.sourcecodetest D/MainActivity: zwm, onResume
2020-01-19 15:11:43.264 7644-7644/com.example.sourcecodetest D/OneFragment: zwm, onResume
2020-01-19 15:11:43.739 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onStop
2020-01-19 15:11:43.739 7644-7644/com.example.sourcecodetest D/SubActivity: zwm, onStop
2020-01-19 15:11:43.740 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onDestroyView
2020-01-19 15:11:43.743 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onDestroy
2020-01-19 15:11:43.743 7644-7644/com.example.sourcecodetest D/SubFragment: zwm, onDetach
2020-01-19 15:11:43.744 7644-7644/com.example.sourcecodetest D/SubActivity: zwm, onDestroy

在回调时,先会回调ActivityA中的onActivityResult()方法,然后再分发回调FragmentA中的onActivityResult()方法。

如果FragmentA中又嵌入一层FragmentAA ,然后从FragmentAA中跳转至ActivityB,那么在FragmentAA中的onActivityResult()方法不能接收到回调,如果想实现多级分发,就得自己在各级Fragment中手动添加分发代码,分发至下一级Fragment中。

十二、状态变迁监听

Fragment的hide和show等状态变迁操作都会反应在相应的回调函数中,我们可以利用这些监听函数做一些界面刷新等功能。较为常见的一个监听函数就是onHiddenChanged()方法,这个方法的变化直接影响着isHidden()方法的返回值。

除了isHidden()方法,还有一个isVisible()方法,也用于判断Fragment的状态,表明Fragment是否对用户可见,如果为 true,必须满足三点条件:

  • 1.Fragment已经被add至Activity中。
  • 2.视图内容已经被关联到window上。
  • 3.没有被隐藏,即isHidden()为false。

注意:onHiddenChanged()方法可以监听hide()和show()操作,与setUserVisibleHint()方法有所不同,后者常见的场景是在ViewPager和Fragment组合的FragmentPagerAdapter中使用。ViewPager滑动时便是通过这个方法改变Fragment的状态,利用这个方法可以实现Fragment懒加载。

//OneFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class OneFragment extends Fragment {
    private static final String TAG = "OneFragment";

    public static OneFragment newInstance(int args){
        Log.d(TAG, "zwm, newInstance, args: " + args);
        OneFragment oneFragment = new OneFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("someArgs", args);
        oneFragment.setArguments(bundle);
        return oneFragment;
    }

    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
        Log.d(TAG, "zwm, onInflate");
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "zwm, onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "zwm, onCreate");
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        int args = -1;
        if(bundle != null) {
            args = bundle.getInt("someArgs");
        }
        Log.d(TAG, "zwm, onCreate, args: " + args);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onCreateView");
        View contentView = inflater.inflate(R.layout.fragment_main, null);
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "zwm, onViewCreated");
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "zwm, onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "zwm, onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "zwm, onDetach");
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Log.d(TAG, "zwm, onCreateOptionsMenu");
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        Log.d(TAG, "zwm, onPrepareOptionsMenu");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.d(TAG, "zwm, onHiddenChanged hidden: " + hidden);
        Log.d(TAG, "zwm, isAdded: " + isAdded());
        Log.d(TAG, "zwm, isHidden: " + isHidden());
        Log.d(TAG, "zwm, isVisible: " + isVisible());
    }
}

//SubFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class SubFragment extends Fragment {
    private static final String TAG = "SubFragment";

    public static SubFragment newInstance(int args){
        Log.d(TAG, "zwm, newInstance, args: " + args);
        SubFragment subFragment = new SubFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("someArgs", args);
        subFragment.setArguments(bundle);
        return subFragment;
    }

    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
        Log.d(TAG, "zwm, onInflate");
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "zwm, onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "zwm, onCreate");
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        int args = -1;
        if(bundle != null) {
            args = bundle.getInt("someArgs");
        }
        Log.d(TAG, "zwm, onCreate, args: " + args);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onCreateView");
        View contentView = inflater.inflate(R.layout.fragment_sub, null);
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onViewCreated");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onActivityCreated");
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "zwm, onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "zwm, onDetach");
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Log.d(TAG, "zwm, onCreateOptionsMenu");
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        Log.d(TAG, "zwm, onPrepareOptionsMenu");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.d(TAG, "zwm, onHiddenChanged hidden: " + hidden);
        Log.d(TAG, "zwm, isAdded: " + isAdded());
        Log.d(TAG, "zwm, isHidden: " + isHidden());
        Log.d(TAG, "zwm, isVisible: " + isVisible());
    }
}

//MainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private OneFragment mOneFragment;
    private SubFragment mSubFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "zwm, onCreate");

        mOneFragment = OneFragment.newInstance(99);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.fragment_container, mOneFragment);
        ft.commit();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "zwm, test");
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.hide(mOneFragment);
                if(mSubFragment == null) {
                    mSubFragment = SubFragment.newInstance(9999);
                    ft.add(R.id.fragment_container, mSubFragment);
                } else {
                    ft.show(mSubFragment);
                }
                ft.commit();
            }
        }, 5000);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "zwm, onNewIntent: " + intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }
}

//输出log
2020-01-19 15:35:56.770 12940-12940/com.example.sourcecodetest D/MyApplication: zwm, onCreate
2020-01-19 15:35:56.983 12940-12940/com.example.sourcecodetest D/MainActivity: zwm, onCreate
2020-01-19 15:35:56.985 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, newInstance, args: 99
2020-01-19 15:35:56.997 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, onAttach
2020-01-19 15:35:56.998 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, onCreate
2020-01-19 15:35:56.998 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, onCreate, args: 99
2020-01-19 15:35:56.999 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, onCreateView
2020-01-19 15:35:57.006 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, onViewCreated
2020-01-19 15:35:57.006 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, onActivityCreated
2020-01-19 15:35:57.006 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, onStart
2020-01-19 15:35:57.008 12940-12940/com.example.sourcecodetest D/MainActivity: zwm, onStart
2020-01-19 15:35:57.010 12940-12940/com.example.sourcecodetest D/MainActivity: zwm, onResume
2020-01-19 15:35:57.011 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, onResume
2020-01-19 15:35:57.131 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, onCreateOptionsMenu
2020-01-19 15:35:57.131 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 15:35:57.133 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 15:36:01.993 12940-12940/com.example.sourcecodetest D/MainActivity: zwm, test
2020-01-19 15:36:01.996 12940-12940/com.example.sourcecodetest D/SubFragment: zwm, newInstance, args: 9999
2020-01-19 15:36:02.001 12940-12940/com.example.sourcecodetest D/SubFragment: zwm, onAttach
2020-01-19 15:36:02.003 12940-12940/com.example.sourcecodetest D/SubFragment: zwm, onCreate
2020-01-19 15:36:02.003 12940-12940/com.example.sourcecodetest D/SubFragment: zwm, onCreate, args: 9999
2020-01-19 15:36:02.010 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, onHiddenChanged hidden: true
2020-01-19 15:36:02.010 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, isAdded: true
2020-01-19 15:36:02.010 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, isHidden: true
2020-01-19 15:36:02.010 12940-12940/com.example.sourcecodetest D/OneFragment: zwm, isVisible: false
2020-01-19 15:36:02.011 12940-12940/com.example.sourcecodetest D/SubFragment: zwm, onCreateView
2020-01-19 15:36:02.033 12940-12940/com.example.sourcecodetest D/SubFragment: zwm, onViewCreated
2020-01-19 15:36:02.034 12940-12940/com.example.sourcecodetest D/SubFragment: zwm, onActivityCreated
2020-01-19 15:36:02.034 12940-12940/com.example.sourcecodetest D/SubFragment: zwm, onStart
2020-01-19 15:36:02.035 12940-12940/com.example.sourcecodetest D/SubFragment: zwm, onResume
2020-01-19 15:36:02.037 12940-12940/com.example.sourcecodetest D/SubFragment: zwm, onCreateOptionsMenu
2020-01-19 15:36:02.038 12940-12940/com.example.sourcecodetest D/SubFragment: zwm, onPrepareOptionsMenu

十三、DialogFragment

1.概念

  • DialogFragment本质上是一个Fragment,继承了Fragment的所有特性,同时FragmentManager会管理DialogFragment。
  • 可以在屏幕旋转或按下返回键时更好地处理其生命周期。
  • 在手机配置发生变化的时候,FragmentManager可以负责现场的恢复工作。调用DialogFragment的setArguments(bundle)方法进行数据的设置,可以保证DialogFragment的数据也能恢复。
  • DialogFragment里的onCreateView和onCreateDIalog两个方法,onCreateView可以用来创建自定义Dialog,onCreateDialog可以用来创建系统原生Dialog。可以在一个类中管理2种不同的Dialog。

2.使用

方法1:

//fragment_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is dialog fragment layout"/>
</LinearLayout>

//MyDialogFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

public class MyDialogFragment extends DialogFragment {
    private static final String TAG = "MyDialogFragment";

    public static MyDialogFragment newInstance(int num) {
        MyDialogFragment f = new MyDialogFragment();
        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        Log.d(TAG, "zwm, onCreateView");
        View view = inflater.inflate(R.layout.fragment_dialog, container);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getDialog().getWindow().setBackgroundDrawableResource(R.drawable.background); //对话框背景
        getDialog().getWindow().setLayout(500,200); //宽高
    }
}

//background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorAccent"/>
</shape>

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is main activity layout"/>
</LinearLayout>

//MainActivity
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "zwm, onCreate");

        MyDialogFragment fragment= MyDialogFragment.newInstance(99);
        fragment.show(getSupportFragmentManager(), "MyDialogFragment");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "zwm, onNewIntent: " + intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }
}

//输出log
2020-01-19 16:37:44.259 22233-22233/com.example.sourcecodetest D/MyApplication: zwm, onCreate
2020-01-19 16:37:45.266 22233-22233/com.example.sourcecodetest D/MainActivity: zwm, onCreate
2020-01-19 16:37:45.412 22233-22233/com.example.sourcecodetest D/MyDialogFragment: zwm, onCreateView
2020-01-19 16:37:45.509 22233-22233/com.example.sourcecodetest D/MainActivity: zwm, onStart
2020-01-19 16:37:45.556 22233-22233/com.example.sourcecodetest D/MainActivity: zwm, onResume

方法2:

//fragment_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is dialog fragment layout"/>
</LinearLayout>

//MyDialogFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

public class MyDialogFragment extends DialogFragment {
    private static final String TAG = "MyDialogFragment";

    public static MyDialogFragment newInstance(int num) {
        MyDialogFragment f = new MyDialogFragment();
        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);
        return f;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onCreateDialog");
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("对话框");
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_dialog, null);
        builder.setView(view);
        builder.setPositiveButton("确定", null);
        builder.setNegativeButton("取消", null);
        return builder.create();
    }
}

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is main activity layout"/>
</LinearLayout>

//MainActivity
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "zwm, onCreate");

        MyDialogFragment fragment= MyDialogFragment.newInstance(99);
        fragment.show(getSupportFragmentManager(), "MyDialogFragment");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "zwm, onNewIntent: " + intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }
}

//输出log
2020-01-19 16:45:57.709 25935-25935/com.example.sourcecodetest D/MyApplication: zwm, onCreate
2020-01-19 16:45:58.232 25935-25935/com.example.sourcecodetest D/MainActivity: zwm, onCreate
2020-01-19 16:45:58.590 25935-25935/com.example.sourcecodetest D/MyDialogFragment: zwm, onCreateDialog
2020-01-19 16:45:58.786 25935-25935/com.example.sourcecodetest D/MainActivity: zwm, onStart
2020-01-19 16:45:58.873 25935-25935/com.example.sourcecodetest D/MainActivity: zwm, onResume

相关链接

Fragment启动流程

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,185评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,445评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,684评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,564评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,681评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,874评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,025评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,761评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,217评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,545评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,694评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,351评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,988评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,778评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,007评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,427评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,580评论 2 349

推荐阅读更多精彩内容

  • 我为何要封装DialogFragment 最近在重构项目代码,项目中创建对话框用的是Dialog,AlertDia...
    牛晓伟阅读 37,293评论 52 181
  • 0 认知 Fragment官方的翻译名为:片段,表示 Activity中的行为或用户界面部分。 相比Activit...
    我是Asha阅读 2,932评论 2 25
  • 1、对比v4包与app包下的Fragment,有哪些不同点,使用时该注意哪些? ①android.support....
    Yangxy_Lazy阅读 1,114评论 0 1
  • 作为一名小顾问,对于Oracle EBS的实施,一般就是按照PM设定的计划执行,领导的计划排到哪就干什么活,到si...
    namelessdu阅读 2,396评论 0 2
  • 想親近,道理沒有用! 想親近,方法沒有用! 想親近,唯有用心! 想親近,唯有感受對方的感受! 想親近,唯有感知到孩...
    范韜阅读 111评论 0 0