2014-04-22 40 views
2

我是手机编程的新手,我现在有一些dificults。 我想写一些东西来设置密码DialogPrefence。 我的问题是,如何从对话框中获取事件OnClick OK如何让DialogPreference POSITIVE_BUTTON在OnClick上工作?

这里是我的代码:

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 

      } 
     }); 


    } 
} 

回答

12

您需要实现DialogInterface.OnClickListener和处理每个按钮

OnClick事件创建自定义DialogPreference类这样

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 
    } 
} 
} 
+0

非常感谢!它像一个魅力! –

+0

setNegativeButtonText(“CANCEL”); – Pawel

0

要显示一个警告对话框,您可以使用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(); 
0

,如果我理解正确的话,你需要知道在另一个类(而不是在SS1_Senha)键按下事件。为此,您可以使用侦听器(观察者)模式或处理程序。