2016-02-29 44 views
0

我想爲對話框方法創建一個函數,並在以後重用函數。如何在對話框中對齊消息並重用該功能?

代碼的函數內創建一個對話框:

private void alertView(String message) { 
    AlertDialog.Builder dialog = new AlertDialog.Builder(this); 

    dialog.setTitle("Hello") 
      .setIcon(R.drawable.ic_launcher) 
      .setMessage(message) 
      .setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialoginterface, int i){ 
       } 
      }).show(); 
} 

的代碼來調用這個函數:

alertView("My message"); 

這工作得很好,但我想我中心消息。我已經尋找解決方案,並使用各種方法,如:

AlertDialog alert = dialog.show(); 
    TextView messageText =(TextView)alert.findViewById(android.R.id.message); 
    messageText.setGravity(Gravity.CENTER); 
    messageText.setTextColor(Color.RED) 

沒有用。有人能幫助我嗎?

+0

http://developer.android.com/guide/topics/ui/dialogs.html向下滾動到「創建自定義佈局」。 – Fildor

+0

據我所知,'Alerts'將會是左向的,而'Simple dialogs'將會是集中的。 請檢查[this](https://www.google.com/design/spec/components/dialogs.html#dialogs-simple-menus)Material Design文檔。 –

回答

0

發現從這個網站對我的問題的解決方案:http://examples.javacodegeeks.com/android/core/ui/dialog/android-custom-dialog-example/

創建的XML佈局在網站上描述的,在我的Java類做了一個變化不大的代碼:

private void alertView(String message) { 
    //create a dialog component 
    final Dialog dialog = new Dialog(this); 

    //tell the dialog to use the dialog.xml as its layout description 
    dialog.setContentView(R.layout.dialog); 
    dialog.setTitle("your title"); 

    TextView txt = (TextView) dialog.findViewById(R.id.txt); 
    txt.setText(message); 
    Button dialogButton = (Button)dialog.findViewById(R.id.dialogButton); 
    dialogButton.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      mUartCom.write("D"); //change this 
     } 
    }); 

    dialog.show(); 

} 

,然後我通過更改消息多次重複使用此功能:

alertView("Please select one of the red icons to begin");