要使用AlertDialog.Builder設(shè)置標(biāo)題,請遵循以下步驟:
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
showDialog()
,用于創(chuàng)建和顯示AlertDialog:public void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("您的標(biāo)題"); // 在這里設(shè)置標(biāo)題
builder.setMessage("您的消息"); // 在這里設(shè)置對話框的消息
// 設(shè)置PositiveButton(確定按鈕)
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 處理PositiveButton的點(diǎn)擊事件
}
});
// 設(shè)置NegativeButton(取消按鈕)
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 處理NegativeButton的點(diǎn)擊事件
}
});
// 創(chuàng)建并顯示AlertDialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
<Button
android:id="@+id/button_show_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="顯示對話框" />
onCreate()
方法中為按鈕設(shè)置OnClickListener,并調(diào)用showDialog()
方法:@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonShowDialog = findViewById(R.id.button_show_dialog);
buttonShowDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog();
}
});
}
現(xiàn)在,當(dāng)您運(yùn)行應(yīng)用程序并單擊“顯示對話框”按鈕時(shí),將顯示一個(gè)帶有指定標(biāo)題的AlertDialog。