Dialog的使用
2018.07.20
Grooter
热度 12℃
以Fragment作为对话框载体:
eg:
LufyDialogFragment.class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import io.githubs.grooters.luffy.R;
public class LufyDialogFragment extends DialogFragment { private static final String TAG=LufyDialogFragment.class.getSimpleName(); private InfoFromDialog infoFromDialog=null; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setTitle(R.string.alertDialog_title) .setView(LayoutInflater.from(getActivity()).inflate(R.layout.view_dialog,null)) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Log.i(TAG,"onClick"); if(infoFromDialog!=null){ Log.i(TAG,"infoFromDialog"); infoFromDialog.getDialogInfo("a","b"); } } }) .create(); } public interface InfoFromDialog{ void getDialogInfo(String a,String b); } public void setInfoFromDialog(InfoFromDialog infoFromDialog){ this.infoFromDialog=infoFromDialog; } }
|
MainActivity,class:
1 2 3 4 5 6 7 8 9
| FragmentManager manager=getFragmentManager(); LufyDialogFragment dialogFragment=new LufyDialogFragment(); dialogFragment.setInfoFromDialog(this); dialogFragment.show(manager,"I am FragmentDialog");
@Override public void getDialogInfo(String a,String b) { Log.i(TAG,a+" "+b); }
|
new AlertDialog.Builder(getActivity()).setView方法用来自定义对话框视图
InfoFromDialog是用于传递数据给MainActivity的接口,该接口在MainActivity中重写,故在MainActivity中可以通过接口方法参数拿到LufyDialogFragment中的数据,setInfoFromDialog方法用来给LufyDialogFragment提供MainActivity的上下文,使LufyDialogFragment能调用经MainActivity重写过的接口方法。
注意:
作为对话框的布局视图,线性布局的match_parent是无效的,需要用相对布局
v1.5.2