2012-01-17 132 views
3

我剛剛添加了一個警報對話框,當單擊後退按鈕時出現。它被設置爲我相信的默認安卓警報。有沒有辦法自定義警告對話框的外觀如改變背景或將drawable設置爲背景?我是新手,所以我不知道該怎麼做。謝謝,我的代碼低於我用於警報對話框。警報對話框自定義

警告對話框:

public boolean onKeyDown(int keyCode, KeyEvent event) { 
     //Handle the back button 
     if(keyCode == KeyEvent.KEYCODE_BACK) { 
      //Ask the user if they want to quit 
      new AlertDialog.Builder(this) 
      .setIcon(android.R.drawable.ic_dialog_alert) 
      .setTitle(R.string.quit) 
      .setMessage(R.string.really_quit) 
      .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { 

       public void onClick(DialogInterface dialog, int which) { 

        //Stop the activity and pause media player 
        mainSound.pause(); 
        MainActivity.this.finish();  
       } 

      }) 
      .setNegativeButton(R.string.no, null) 
      .show(); 

      return true; 
     } 
     else { 
      return super.onKeyDown(keyCode, event); 
     } 

    } 

回答

3

這樣的..

創建XML佈局

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      android:id="@+id/dialog_layout_root" 
      android:orientation="vertical" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:padding="10dp" 
      > 

然後你可以用下面的建設者設置您的佈局:

LayoutInflater inflater = getLayoutInflater(); 
View dialoglayout = inflater.inflate(R.layout.dialog_layout, (ViewGroup) findViewById(R.id.dialog_layout_root)); 
AlertDialog.Builder builder = new AlertDialog.Builder(this); 
builder.setView(dialoglayout); 

編輯:

你應該重新安排你的代碼到這樣的東西... 創建AlertDialog.Builder在課堂級別。

private AlertDialog.Builder builder; 

在你的onCreate()創建AlertDialog

LayoutInflater inflater = getLayoutInflater(); 
    View dialoglayout = inflater.inflate(R.layout.dialog_layout, (ViewGroup)  findViewById(R.id.dialog_layout_root)); 


    //Ask the user if they want to quit 
     builder 
     .setIcon(android.R.drawable.ic_dialog_alert) 
     .setTitle(R.string.quit) 
     .setMessage(R.string.really_quit) 
     .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { 

      public void onClick(DialogInterface dialog, int which) { 

       //Stop the activity and pause media player 
       mainSound.pause(); 
       MainActivity.this.finish();  
      } 

     }) 
     .setNegativeButton(R.string.no, null) 
     .setView(dailogLayout); 





public boolean onKeyDown(int keyCode, KeyEvent event) { 
    //Handle the back button 
    if(keyCode == KeyEvent.KEYCODE_BACK) { 

    builder.show(); 

     return true; 
    } 
    else { 
     return super.onKeyDown(keyCode, event); 
    } 

} 
+0

在我的生成器中,我會放底部代碼? – 2012-01-17 00:40:10

+0

查看我的編輯 – 2012-01-17 00:59:54

+0

非常感謝。那樣做了。 – 2012-01-17 01:57:39

1

我會一直在這裏寫了一個更詳細的答案,但谷歌寫這篇教程更好的比我能:只是去http://developer.android.com/guide/topics/ui/dialogs.html,和請轉至創建自定義對話框。 這可能是谷歌爲Android寫的最好的教程之一。

+0

謝謝,我檢查了它是非常有幫助的。 – 2012-01-17 01:57:18