如何在对话框功能中对齐消息并重用该功能?

时间:2016-02-29 11:46:01

标签: java android alertdialog

我想为对话框方法创建一个函数,并在以后重用该函数。

在函数中创建对话框的代码:

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)

没有任何作用。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分: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");