2011-06-14 21 views
2

我是Java/Android開發人員的新手,我習慣於在學習新平臺時創建工具庫,並在其中爲非常常見的任務添加函數。在這種情況下,確定/取消對話框。通過單一方法調用的對話框

我想達到的目標是這樣的:

if (tools.ask("Are you sure")) { 
    //do something 
} 
else { 
    //don't do it 
} 

tools.ask()應建立並顯示確定/取消的對話中,如果用戶點擊OK返回true,否則(點擊取消,後退按鈕點擊,應用程序終止,不管)返回false。

我看着AlertDialog,我知道如何用X行代碼實現它。但由於這是事件驅動,我不知道如何將它放在具有返回值的方法中。

這有可能嗎?

在此先感謝!

回答

2

您需要有實現事件偵聽器的類。這些由事件監聽器指定的實現方法將在UI事件發生時被回調,這不會導致UI線程掛起。

例如

public class MyActivity extends Activity implements OnClickListener 

,然後實現方法

public void onClick(View v) { 
    int id = v.getId(); 

    if (id == R.id.widget_id){ 
     //Do something 
    } 
} 

還需要將監聽器添加到UI控件

widget.setOnClickListener(this); 

看看這裏:http://developer.android.com/guide/topics/ui/ui-events.html

2

您不應該嘗試創建阻塞並等待結果的方法,因爲這樣會阻塞UI線程,然後操作系統會向用戶報告您的應用程序沒有響應。

你的UI應該是事件驅動的。

+0

我不得不同意 – sherif 2011-06-14 14:15:16

+0

確定。我習慣於Windows中的「模態對話框」,它只阻止調用表單(活動),而不是整個UI。方便的東西。 – natraj 2011-06-16 20:38:31

0

看看下面的課。我建議你在你的活動中做事件處理部分。調用爲您創建所需警報對話框的函數。

公共類AlertUtil {

/** Single AlertUtil Object*/ 
private static AlertUtil mAlertUtil; 

/** 
* method that prepares Dialog 
* @param context 
* @param title 
* @param message 
* @return Alert Dialog 
*/ 
public AlertDialog getAlertDialog1(Context context, int title,int icon, 
     String message){ 

    AlertDialog alert = new AlertDialog.Builder(context).create(); 
    alert.setTitle(title); 
    alert.setIcon(icon); 
    alert.setMessage(message); 
    alert.setCancelable(true); 

    return alert; 
} 


public static void setAlertUtil(AlertUtil mAlertUtil) { 
    AlertUtil.mAlertUtil = mAlertUtil; 
} 

public static AlertUtil getAlertUtil() { 
    if(mAlertUtil == null){ 
     setAlertUtil(new AlertUtil()); 
    } 
    return mAlertUtil; 
} 

}

相關問題