使用DialogFragment實現dialog的自定義布局最大的好處是可以更好控制dialog的生命周期。
TestFragment的代碼:
public class TestFragment extends DialogFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_test, container, false); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = super.onCreateDialog(savedInstanceState);
//設置actionbar的隱藏 //dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); return dialog; } }
fragment_test的布局
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.topsports.testapplication.BigImageFragment"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="刪除"/> </FrameLayout>
在TestFragment的onCreateDialog方法中引入自定義布局。
使用DialogFragment:
TestFragment dialog=new TestFragment();dialog.show(getSupportFragmentManager(),"dialog");
show的第一個參數是FragmentManager(這里使用的是android.support.v4.app.DialogFragment,如果使用的是android.app.DialogFragment將getSupportFragmentManager方法替換成getFragmentManager),第二個參數是給這個dialog設置一個Tag。
PS:如果要實現一個自定義dialog除了使用dialogFragment,還可以用dialog的形式顯示activity,可以在AndroidManifest.xml里面設置activity的theme為“@android:style/Theme.Holo.Dialog”。
<activity android:name=".TestActivity" android:theme="@android:style/Theme.Holo.Dialog" />