Android 防止在单击按钮时关闭DialogFragment
我有一个带有自定义视图的DialogFragment,其中包含两个文本字段,用户在其中输入用户名和密码。单击肯定按钮时,我想验证用户是否确实在关闭对话框之前输入了一些内容Android 防止在单击按钮时关闭DialogFragment,android,dialog,onclick,android-dialogfragment,Android,Dialog,Onclick,Android Dialogfragment,我有一个带有自定义视图的DialogFragment,其中包含两个文本字段,用户在其中输入用户名和密码。单击肯定按钮时,我想验证用户是否确实在关闭对话框之前输入了一些内容 public class AuthenticationDialog extends DialogFragment { public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new
public class AuthenticationDialog extends DialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.authentication_dialog, null))
.setPositiveButton(getResources().getString(R.string.login), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO
}
})
.setNegativeButton(getResources().getString(R.string.reset), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO
}
});
return builder.create();
}
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// your dialog setup, just leave the OnClick-listeners empty here and use the ones below
final AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(final DialogInterface dialog) {
Button positiveButton = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
// TODO - call 'dismiss()' only if you need it
}
});
Button negativeButton = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_NEGATIVE);
// same for negative (and/or neutral) button if required
}
});
return dialog;
}
那么,如何防止对话框被忽略呢?有什么方法需要重写吗?您可以再次弹出对话框。或者,您可以将正极按钮保持禁用状态,直到两个字段都有输入。如果要在
onCreateVew()中创建布局,这非常容易。如果您使用的是AlertDialog.Builder
类,则可以获得按钮的句柄,如下所示:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
/* ... */
Dialog dialog = builder.create();
Button positiveButton = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE);
/* now you can affect the button */
多亏了Luksprog,我才找到了解决办法
AuthenticationDialog.java:
public class AuthenticationDialog extends DialogFragment implements OnClickListener {
public interface AuthenticationDialogListener {
void onAuthenticationLoginClicked(String username, String password);
void onAuthenticationResetClicked(String username);
}
private AuthenticationDialogListener mListener;
private EditText mUsername;
private EditText mPassword;
private Button mReset;
private Button mLogin;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.authentication_dialog, container);
this.getDialog().setTitle(R.string.login_title);
mUsername = (EditText) view.findViewById(R.id.username_field);
mPassword = (EditText) view.findViewById(R.id.password_field);
mReset = (Button) view.findViewById(R.id.reset_button);
mLogin = (Button) view.findViewById(R.id.login_button);
mReset.setOnClickListener(this);
mLogin.setOnClickListener(this);
return view;
}
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (AuthenticationDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement AuthenticationDialogListener");
}
}
public void onClick(View v) {
if (v.equals(mLogin)) {
if (mUsername.getText().toString().length() < 1 || !mUsername.getText().toString().contains("@")) {
Toast.makeText(getActivity(), R.string.invalid_email, Toast.LENGTH_SHORT).show();
return;
} else if (mPassword.getText().toString().length() < 1) {
Toast.makeText(getActivity(), R.string.invalid_password, Toast.LENGTH_SHORT).show();
return;
} else {
mListener.onAuthenticationLoginClicked(mUsername.getText().toString(), mPassword.getText().toString());
this.dismiss();
}
} else if (v.equals(mReset)) {
mListener.onAuthenticationResetClicked(mUsername.getText().toString());
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/username_field"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="@string/username"
/>
<EditText
android:id="@+id/password_field"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="12dp"
android:fontFamily="sans-serif"
android:hint="@string/password"
/>
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="?android:attr/dividerVertical"
/>
<LinearLayout
style="?android:attr/buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="0dp"
android:measureWithLargestChild="true" >
<Button
android:id="@+id/reset_button"
style="?android:attr/buttonBarButtonStyle"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1.0"
android:text="@string/reset"
/>
<Button
android:id="@+id/login_button"
style="?android:attr/buttonBarButtonStyle"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1.0"
android:text="@string/login"
/>
</LinearLayout>
</LinearLayout>
公共类AuthenticationDialog扩展了DialogFragment实现OnClickListener{
公共接口身份验证DialogListener{
验证登录无效(字符串用户名、字符串密码);
在AuthenticationResetClicked上无效(字符串用户名);
}
私有身份验证DialogListener mListener;
私人编辑文本博物馆名称;
私人编辑文本mPassword;
专用按钮mReset;
私有按钮登录;
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
视图=充气机。充气(R.layout.authentication\u对话框,容器);
this.getDialog().setTitle(R.string.login\u title);
mUsername=(EditText)view.findViewById(R.id.username\u字段);
mPassword=(EditText)view.findViewById(R.id.password\u字段);
mReset=(按钮)view.findViewById(R.id.reset_按钮);
mLogin=(按钮)view.findviewbyd(R.id.login\u按钮);
mReset.setOnClickListener(此);
mLogin.setOnClickListener(这个);
返回视图;
}
公共事务主任(活动){
超级转速计(活动);
//验证主机活动是否实现了回调接口
试一试{
//实例化NoticeDialogListener,以便我们可以向主机发送事件
mListener=(AuthenticationDialogListener)活动;
}catch(ClassCastException e){
//活动未实现接口,引发异常
抛出新的ClassCastException(activity.toString()
+“必须实现AuthenticationDialogListener”);
}
}
公共void onClick(视图v){
如果(v.equals(mLogin)){
如果(mUsername.getText().toString().length()<1||!mUsername.getText().toString().contains(“@”)){
Toast.makeText(getActivity(),R.string.invalid_email,Toast.LENGTH_SHORT).show();
返回;
}else if(mPassword.getText().toString().length()<1){
Toast.makeText(getActivity(),R.string.invalid_密码,Toast.LENGTH_SHORT.show();
返回;
}否则{
mListener.onAuthenticationLoginClicked(mUsername.getText().toString(),mPassword.getText().toString());
这个。解散();
}
}否则如果(v等于(mReset)){
mListener.onAuthenticationResetClicked(mUsername.getText().toString());
}
}
}
身份验证\u dialog.xml:
public class AuthenticationDialog extends DialogFragment implements OnClickListener {
public interface AuthenticationDialogListener {
void onAuthenticationLoginClicked(String username, String password);
void onAuthenticationResetClicked(String username);
}
private AuthenticationDialogListener mListener;
private EditText mUsername;
private EditText mPassword;
private Button mReset;
private Button mLogin;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.authentication_dialog, container);
this.getDialog().setTitle(R.string.login_title);
mUsername = (EditText) view.findViewById(R.id.username_field);
mPassword = (EditText) view.findViewById(R.id.password_field);
mReset = (Button) view.findViewById(R.id.reset_button);
mLogin = (Button) view.findViewById(R.id.login_button);
mReset.setOnClickListener(this);
mLogin.setOnClickListener(this);
return view;
}
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (AuthenticationDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement AuthenticationDialogListener");
}
}
public void onClick(View v) {
if (v.equals(mLogin)) {
if (mUsername.getText().toString().length() < 1 || !mUsername.getText().toString().contains("@")) {
Toast.makeText(getActivity(), R.string.invalid_email, Toast.LENGTH_SHORT).show();
return;
} else if (mPassword.getText().toString().length() < 1) {
Toast.makeText(getActivity(), R.string.invalid_password, Toast.LENGTH_SHORT).show();
return;
} else {
mListener.onAuthenticationLoginClicked(mUsername.getText().toString(), mPassword.getText().toString());
this.dismiss();
}
} else if (v.equals(mReset)) {
mListener.onAuthenticationResetClicked(mUsername.getText().toString());
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/username_field"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="@string/username"
/>
<EditText
android:id="@+id/password_field"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="12dp"
android:fontFamily="sans-serif"
android:hint="@string/password"
/>
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="?android:attr/dividerVertical"
/>
<LinearLayout
style="?android:attr/buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="0dp"
android:measureWithLargestChild="true" >
<Button
android:id="@+id/reset_button"
style="?android:attr/buttonBarButtonStyle"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1.0"
android:text="@string/reset"
/>
<Button
android:id="@+id/login_button"
style="?android:attr/buttonBarButtonStyle"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1.0"
android:text="@string/login"
/>
</LinearLayout>
</LinearLayout>
为此,请覆盖OnStart()中的默认按钮处理程序
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
builder.setPositiveButton("Test",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
//Do nothing here because we override this button later to change the close behaviour.
//However, we still need this because on older versions of Android unless we
//pass a handler the button doesn't get instantiated
}
});
return builder.create();
}
@Override
public void onStart()
{
super.onStart(); //super.onStart() is where dialog.show() is actually called on the underlying dialog, so we have to do it after this point
AlertDialog d = (AlertDialog)getDialog();
if(d != null)
{
Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Boolean wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if(wantToCloseDialog)
dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
}
}
有关其他对话框类型的更多解释和示例,请参见我的答案。这是Karakuri和Sogger答案的“最佳”解决方案。Karakuri在正确的轨道上,但是只有在按钮已经显示的情况下,您才能以这种方式获得按钮(否则为空,如注释中所述)。这就是为什么Sogger的答案有效,但是我更喜欢使用相同的方法进行设置,即onCreateDialog
,而不是在onStart
中进行设置。解决方案是将按钮的获取包装到对话框的OnShowListener
public class AuthenticationDialog extends DialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.authentication_dialog, null))
.setPositiveButton(getResources().getString(R.string.login), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO
}
})
.setNegativeButton(getResources().getString(R.string.reset), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO
}
});
return builder.create();
}
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// your dialog setup, just leave the OnClick-listeners empty here and use the ones below
final AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(final DialogInterface dialog) {
Button positiveButton = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
// TODO - call 'dismiss()' only if you need it
}
});
Button negativeButton = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_NEGATIVE);
// same for negative (and/or neutral) button if required
}
});
return dialog;
}
如何防止对话框被取消?-不要使用对话框默认的按钮
(使用setPositiveButton
等设置的按钮)。设置自己的按钮
以关闭对话框,并在其OnClickListeners
中实现所需的逻辑。您应该为您的对话框片段发布代码。当我尝试您建议的方法时,从onCreateDialog中获取对自定义视图元素的引用总是返回null。此时对话框不会在屏幕上呈现。相反,尝试将布局R.layout.authentication\u对话框
充气到视图
参考中,然后搜索按钮
:视图v=充气器.充气(R.layout.authentication\u对话框);按钮b=(按钮)v.findviewById(R.id.the_btn_id)
@Luksprog根据你的建议,我找到了一个解决方案。我将在一个答案中发布我的代码,但是如果你想发布一个答案并引用我的答案,我会给你正确的答案。上面注释中的代码不起作用?出于某种原因,如果我在调用builder.create()后但在显示之前尝试调用对话框上的getButton,它将返回null。这对我不起作用d.getButton(Dialog.BUTTON_正值)
返回null。@Travis Christian您的目标必须是旧版本的Android。我之前也遇到过这个问题,我已经更新了我的答案,所以它现在可以在旧版本上使用。您需要在第一次通话中传入一个空白的click listener。很有趣,谢谢。我的目标是15,所以这肯定是最近的变化。我想我只是假设这是一个与旧VS新的问题,因为它是在一个新的电话(IC我想)工作,但我有一个旧的GigeGrice电话,它没有工作,而不定义空白听众。不管怎样,因为添加了空白侦听器,它一直在这两个方面工作。