我想知道如何为我的应用程序创建自定义材质对话框.具体来说,我需要实现这样的目标
我一直在遵循这样的方法:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Sample");
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setonClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
但是,我点击按钮时出现空指针异常.任何教程对我来说都是一个很好的帮助.
解决方法:
编写一个扩展到DialogFragment的新类.
public class CustomDialog extends DialogFragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_dialog,container,false);
getDialog().setTitle("Sample");
Button doneBtn = (Button) mView.findViewById(R.id.done_convert);
doneBtn.setonClickListener(doneAction);
return view;
}
View.OnClickListener doneAction = new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Test",Toast.LENGTH_LONG).show();
}
};
}
然后从您的活动中调用它
FragmentManager fm = getSupportFragmentManager();
CustomDialog custom = new CustomDialog();
custom.show(fm,"");
希望,它会奏效.