2009-12-22 58 views

回答

11

只需捕获所需的异常,然后创建一个包含异常内容的新AlertDialog。

import android.app.Activity; 
import android.app.AlertDialog; 
import android.os.Bundle; 

public class HelloException extends Activity { 
    public class MyException extends Exception { 
     private static final long serialVersionUID = 467370249776948948L; 
     MyException(String message) { 
      super(message); 
     } 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     try { 
      doSomething(); 
     } catch (MyException e) { 
      AlertDialog.Builder dialog = new AlertDialog.Builder(this); 
      dialog.setTitle("MyException Occured"); 
      dialog.setMessage(e.getMessage()); 
      dialog.setNeutralButton("Cool", null); 
      dialog.create().show(); 
     } 
    } 

    private void doSomething() throws MyException { 
     throw new MyException("Hello world."); 
    } 
} 
+0

谢谢,这解决了我的问题。 – dgraziotin 2009-12-22 19:48:44

3

只是为了让其他用户知道: 如果你有一个分开的自定义异常,你要到处使用(模型,控制器等),以及在你的意见,到处传播的自定义异常和添加Trevor的AlertDialog的代码在你的例外规定的方法,传递上下文:

package it.unibz.pomodroid.exceptions; 

import android.app.AlertDialog; 
import android.content.Context; 

public class PomodroidException extends Exception{ 
    /** 
    * 
    */ 
    private static final long serialVersionUID = 1L; 

    // Default constructor 
    // initializes custom exception variable to none 
    public PomodroidException() { 
     // call superclass constructor 
     super();    
    } 

    // Custom Exception Constructor 
    public PomodroidException(String message) { 
     // Call super class constructor 
     super(message); 
    } 


    public void alertUser(Context context){ 
     AlertDialog.Builder dialog = new AlertDialog.Builder(context); 
     dialog.setTitle("WARNING"); 
     dialog.setMessage(this.toString()); 
     dialog.setNeutralButton("Ok", null); 
     dialog.create().show(); 
    } 

} 

在我的片段,方法是alertUser(上下文的背景下)。要在活动中显示警报,只需使用:

try { 
    // ... 
} catch (PomodroidException e) { 
    e.alertUser(this); 
} 

这很容易超载定制AlertDialog的一些部件,如它的标题和按钮上的文字的方法。

希望这可以帮助别人。

相关问题