組件 -- Fragment?-- 2

八篷扩、通信方式

Fragment與Activity通信通常存在三種情形:Activity操作內(nèi)嵌的Fragment坎吻,F(xiàn)ragment操作宿主Activity策严,F(xiàn)ragment操作同屬Activity中的其他Fragment相叁。

由于Activity持有所有內(nèi)嵌的Fragment對象實例(創(chuàng)建實例時保存的Fragment對象,或者通過FragmentManager類提供的findFragmentById()和findFragmentByTag()方法也能獲取到Fragment對象)烦感,所以可以直接操作Fragment;Fragment通過getActivity()方法可以獲取到宿主Activity對象(強(qiáng)制轉(zhuǎn)換類型即可)膛堤,進(jìn)而可以操作宿主Activity手趣;獲取到宿主Activity對象的Fragment便可以操作其他Fragment對象。

雖然上述操作已經(jīng)能夠解決Activity與Fragment的通信問題肥荔,但會造成代碼邏輯紊亂的結(jié)果绿渣,極度不符合編程思想:高內(nèi)聚,低耦合燕耿。Fragment做好自己的事情即可中符,所有涉及到Fragment之間的控制顯示等操作,都應(yīng)交由宿主Activity來統(tǒng)一管理誉帅。我們推薦使用對外開放接口的形式將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 { //定義監(jiān)聽器接口
        void onOneFragmentClick();
    }

    public void setClickListener(IOneFragmentClickListener clickListener) { //設(shè)置監(jiān)聽器
        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(); //調(diào)用監(jiān)聽器方法
        }
    }
}

//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 { //實現(xiàn)監(jiān)聽接口
    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); //設(shè)置監(jiān)聽器
        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() { //覆寫監(jiān)聽方法
        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()引用問題

使用中經(jīng)常會在Fragment中通過getActivity()獲取到宿主Activity對象蚜锨,但稍有不慎便會引發(fā)下面這兩個問題:

  • 1.Activity的實例銷毀問題
    Fragment中存在類似網(wǎng)絡(luò)請求之類的異步耗時任務(wù)档插,當(dāng)該任務(wù)執(zhí)行完畢回調(diào)Fragment的方法并用到宿主Activity對象時,很有可能宿主Activity對象已經(jīng)銷毀亚再,從而引發(fā)NullPointException等異常郭膛。所以,異步回調(diào)時需要注意添加空值等判斷(例如:fragment.isAdd()针余,getActivity() != null等)饲鄙,或者在Fragment創(chuàng)建實例時就通過getActivity().getApplicationContext()方法保存整個應(yīng)用的上下文對象,再來使用圆雁。
  • 2.內(nèi)存泄漏問題
    如果Fragment持有宿主Activity的引用忍级,會導(dǎo)致宿主Activity無法回收,造成內(nèi)存泄漏伪朽。所以轴咱,如果可以的話,盡量不要在Fragment中持有宿主Activity的引用烈涮。

為了解決Context上下文引用的問題朴肺,F(xiàn)ragment提供了一個onAttach(context)方法,在此方法中我們可以獲取到Context對象坚洽,如:

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

十戈稿、Fragment重疊問題

當(dāng)Activity被異常銷毀發(fā)生重建時,會重新執(zhí)行onCreate()方法讶舰,并再次執(zhí)行Fragment的創(chuàng)建和顯示等操作鞍盗,而之前已經(jīng)存在的Fragment實例也會銷毀再次創(chuàng)建需了,這就與Activity中onCreate()方法里面第二次創(chuàng)建的Fragment同時顯示從而發(fā)生UI重疊的問題。為解決這個問題需要在Activity中創(chuàng)建Fragment實例時添加一個判斷:

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

十一般甲、onActivityResult()

Fragment類提供有startActivityForResult()方法用于Activity間的頁面跳轉(zhuǎn)和數(shù)據(jù)回傳肋乍,其實內(nèi)部也是調(diào)用Activity的對應(yīng)方法。但是在頁面返回時需要注意Fragment沒有提供setResult()方法敷存,可以通過宿主Activity實現(xiàn)墓造。

例如,在ActivityA中的FragmentA里面調(diào)用startActivityForResult()跳轉(zhuǎn)至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

在回調(diào)時,先會回調(diào)ActivityA中的onActivityResult()方法挽牢,然后再分發(fā)回調(diào)FragmentA中的onActivityResult()方法谱煤。

如果FragmentA中又嵌入一層FragmentAA 摊求,然后從FragmentAA中跳轉(zhuǎn)至ActivityB禽拔,那么在FragmentAA中的onActivityResult()方法不能接收到回調(diào),如果想實現(xiàn)多級分發(fā)室叉,就得自己在各級Fragment中手動添加分發(fā)代碼睹栖,分發(fā)至下一級Fragment中。

十二茧痕、狀態(tài)變遷監(jiān)聽

Fragment的hide和show等狀態(tài)變遷操作都會反應(yīng)在相應(yīng)的回調(diào)函數(shù)中野来,我們可以利用這些監(jiān)聽函數(shù)做一些界面刷新等功能。較為常見的一個監(jiān)聽函數(shù)就是onHiddenChanged()方法踪旷,這個方法的變化直接影響著isHidden()方法的返回值曼氛。

除了isHidden()方法,還有一個isVisible()方法令野,也用于判斷Fragment的狀態(tài)舀患,表明Fragment是否對用戶可見,如果為 true气破,必須滿足三點條件:

  • 1.Fragment已經(jīng)被add至Activity中聊浅。
  • 2.視圖內(nèi)容已經(jīng)被關(guān)聯(lián)到window上。
  • 3.沒有被隱藏现使,即isHidden()為false低匙。

注意:onHiddenChanged()方法可以監(jiān)聽hide()和show()操作,與setUserVisibleHint()方法有所不同碳锈,后者常見的場景是在ViewPager和Fragment組合的FragmentPagerAdapter中使用顽冶。ViewPager滑動時便是通過這個方法改變Fragment的狀態(tài),利用這個方法可以實現(xiàn)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本質(zhì)上是一個Fragment佩迟,繼承了Fragment的所有特性,同時FragmentManager會管理DialogFragment竿屹。
  • 可以在屏幕旋轉(zhuǎn)或按下返回鍵時更好地處理其生命周期报强。
  • 在手機(jī)配置發(fā)生變化的時候,F(xiàn)ragmentManager可以負(fù)責(zé)現(xiàn)場的恢復(fù)工作拱燃。調(diào)用DialogFragment的setArguments(bundle)方法進(jìn)行數(shù)據(jù)的設(shè)置秉溉,可以保證DialogFragment的數(shù)據(jù)也能恢復(fù)。
  • DialogFragment里的onCreateView和onCreateDIalog兩個方法碗誉,onCreateView可以用來創(chuàng)建自定義Dialog召嘶,onCreateDialog可以用來創(chuàng)建系統(tǒng)原生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

相關(guān)鏈接

Fragment啟動流程

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市尝苇,隨后出現(xiàn)的幾起案子铛只,更是在濱河造成了極大的恐慌,老刑警劉巖糠溜,帶你破解...
    沈念sama閱讀 211,817評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件淳玩,死亡現(xiàn)場離奇詭異,居然都是意外死亡非竿,警方通過查閱死者的電腦和手機(jī)蜕着,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,329評論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來红柱,“玉大人承匣,你說我怎么就攤上這事〈盖模” “怎么了韧骗?”我有些...
    開封第一講書人閱讀 157,354評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長铁蹈。 經(jīng)常有香客問我宽闲,道長,這世上最難降的妖魔是什么握牧? 我笑而不...
    開封第一講書人閱讀 56,498評論 1 284
  • 正文 為了忘掉前任容诬,我火速辦了婚禮,結(jié)果婚禮上沿腰,老公的妹妹穿的比我還像新娘览徒。我一直安慰自己,他們只是感情好颂龙,可當(dāng)我...
    茶點故事閱讀 65,600評論 6 386
  • 文/花漫 我一把揭開白布习蓬。 她就那樣靜靜地躺著纽什,像睡著了一般。 火紅的嫁衣襯著肌膚如雪躲叼。 梳的紋絲不亂的頭發(fā)上芦缰,一...
    開封第一講書人閱讀 49,829評論 1 290
  • 那天,我揣著相機(jī)與錄音枫慷,去河邊找鬼让蕾。 笑死,一個胖子當(dāng)著我的面吹牛或听,可吹牛的內(nèi)容都是我干的探孝。 我是一名探鬼主播,決...
    沈念sama閱讀 38,979評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼誉裆,長吁一口氣:“原來是場噩夢啊……” “哼顿颅!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起足丢,我...
    開封第一講書人閱讀 37,722評論 0 266
  • 序言:老撾萬榮一對情侶失蹤粱腻,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后霎桅,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體栖疑,經(jīng)...
    沈念sama閱讀 44,189評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,519評論 2 327
  • 正文 我和宋清朗相戀三年滔驶,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片卿闹。...
    茶點故事閱讀 38,654評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡揭糕,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出锻霎,到底是詐尸還是另有隱情著角,我是刑警寧澤,帶...
    沈念sama閱讀 34,329評論 4 330
  • 正文 年R本政府宣布旋恼,位于F島的核電站吏口,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏冰更。R本人自食惡果不足惜产徊,卻給世界環(huán)境...
    茶點故事閱讀 39,940評論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蜀细。 院中可真熱鬧舟铜,春花似錦、人聲如沸奠衔。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,762評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至痊夭,卻和暖如春刁岸,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背她我。 一陣腳步聲響...
    開封第一講書人閱讀 31,993評論 1 266
  • 我被黑心中介騙來泰國打工难捌, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人鸦难。 一個月前我還...
    沈念sama閱讀 46,382評論 2 360
  • 正文 我出身青樓根吁,卻偏偏與公主長得像,于是被迫代替她去往敵國和親合蔽。 傳聞我的和親對象是個殘疾皇子击敌,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,543評論 2 349

推薦閱讀更多精彩內(nèi)容

  • 我為何要封裝DialogFragment 最近在重構(gòu)項目代碼沃斤,項目中創(chuàng)建對話框用的是Dialog,AlertDia...
    牛曉偉閱讀 37,293評論 52 181
  • 0 認(rèn)知 Fragment官方的翻譯名為:片段刃宵,表示 Activity中的行為或用戶界面部分衡瓶。 相比Activit...
    我是Asha閱讀 2,932評論 2 25
  • 1、對比v4包與app包下的Fragment牲证,有哪些不同點哮针,使用時該注意哪些? ①android.support....
    Yangxy_Lazy閱讀 1,114評論 0 1
  • 作為一名小顧問,對于Oracle EBS的實施坦袍,一般就是按照PM設(shè)定的計劃執(zhí)行十厢,領(lǐng)導(dǎo)的計劃排到哪就干什么活,到si...
    namelessdu閱讀 2,393評論 0 2
  • 想親近捂齐,道理沒有用蛮放! 想親近,方法沒有用奠宜! 想親近包颁,唯有用心! 想親近压真,唯有感受對方的感受娩嚼! 想親近,唯有感知到孩...
    范韜閱讀 111評論 0 0