更改AlertDialog的标题标题

时间:2017-12-11 03:13:22

标签: android android-layout android-theme

我正在尝试更改Alertdialog框的标题标题,但输出不是我想要的。我在styles.xml中创建了以下样式:

<style name="question_dialog" 
  parent="@android:style/Theme.Holo.Dialog">
    <item name="android:windowTitleStyle">@style/question_dialog_title</item>
</style>

<style name="question_dialog_title" parent="android:Widget.TextView">
<item name="android:background">#5cc5cc</item>
<item name="android:textSize">21sp</item>
<item name="android:textColor">#ffffff</item>
</style>

java代码如下:

new AlertDialog.Builder(this, 
R.style.question_dialog).setTitle("Assam Quiz" ). 
setMessage("Hello world Hello world"). 
setPositiveButton("OK", (dialog, which) - > 
{dialog.dismisd();
}).show();
}

附上AlertDialog图像。 enter image description here

1 个答案:

答案 0 :(得分:2)

超出样式 - 我认为你的对话框设置了一些标题布局,阻止标题位于顶部,但如果是这种情况 - 你可以很容易地{{ 3}}对于对话框标题只给它标题布局,所以你将拥有对话框标题的完全控制权:

// creating the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// getting dialog context
Context mContext = builder.getContext();
// building the inflater
LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
// inflate the dialog header layout
View mView = mLayoutInflater.inflate(R.layout.simple_dialog_header, null);
// get the TextView for the header (contained in the header layout)
TextView mTextView = (TextView) mView.findViewById(R.id.title_text);
// set the text for that TextView
mTextView.setText(message);
// set the custom header view for the dialog
builder.setCustomTitle(mView);
/*
here you can set positive , negative ,neutral buttons
or set the dialog message or any attribute you want
*/
// finally, show the dialog
builder.show();

和标题布局(R.layout.simple_dialog_header):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/primary"
    android:orientation="vertical"
    android:paddingBottom="15dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="15dp">

    <TextView
        android:id="@+id/title_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:maxLines="1"
        android:textAlignment="center"
        android:textColor="@color/primary"
        android:textSize="16sp"
        android:textStyle="bold" />

</LinearLayout>