Java 如何让DialogPreference按钮在OnClick上工作?
我正在尝试写一些东西,用Java 如何让DialogPreference按钮在OnClick上工作?,java,android,events,mobile,onclick,Java,Android,Events,Mobile,Onclick,我正在尝试写一些东西,用DialogPrefence设置密码。 如何从对话框中获取onClick()事件的OK按钮 代码如下: package com.kontrol.app; import android.content.Context; import android.content.DialogInterface; import android.preference.DialogPreference; import android.util.AttributeSet; public cl
DialogPrefence
设置密码。
如何从对话框中获取onClick()
事件的OK按钮
代码如下:
package com.kontrol.app;
import android.content.Context;
import android.content.DialogInterface;
import android.preference.DialogPreference;
import android.util.AttributeSet;
public class SS1_Senha extends DialogPreference implements DialogInterface.OnClickListener{
public SS1_Senha(Context context, AttributeSet attrs) {
super(context, attrs);
setPersistent(false);
setDialogLayoutResource(R.layout.ss1_senha);
setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Action after OK
}
});
}
}
要显示警报对话框,可以使用AlertDialog.builder。 例如:
AlertDialog alertDialog = new AlertDialog.Builder(
AlertDialogActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("My Message");
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
如果我理解正确,您需要了解其他类中的按键事件(不在SS1_Senha中)。为此,您可以使用侦听器(观察者)模式或处理程序。您需要实现
对话框界面。OnClickListener
并处理每个按钮的OnClick
事件
像这样创建一个自定义的对话框首选项类
public class CustomDialogPreference extends DialogPreference implements DialogInterface.OnClickListener{
public CustomDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setPersistent(false);
setDialogLayoutResource(R.layout.image_dialog);
setPositiveButtonText("OK");
setNegativeButtonText("CANCEL");
}
@Override
public void onClick(DialogInterface dialog, int which){
if(which == DialogInterface.BUTTON_POSITIVE) {
// do your stuff to handle positive button
}else if(which == DialogInterface.BUTTON_NEGATIVE){
// do your stuff to handle negative button
}
}
}
setNegativeButtonText(“取消”);