2014-04-22 39 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)鍵按下事件。爲此,您可以使用偵聽器(觀察者)模式或處理程序。