Мне нужно выровнять текст по середине в андроиде alertdialog. но я не могу найти способ ... Кто-нибудь знает, как это сделать?android: как выровнять сообщение в alertDialog?
ответ
Попросите свой TextView заполнить родительский элемент и придать ему центр тяжести.
<TextView ... android:layout_width="fill_parent" android:gravity="center" />
Вам понадобится использовать один из конструкторов, предназначенных для AlertDialog в Android, при его создании.
AlertDialog (контекстный контекст, int theme) Построить AlertDialog, который использует явную тему.
Этот link поможет вам. Поскольку вы хотите, чтобы текст был центрирован, вам нужно было бы указать атрибут тяжести, значение «center».
попробовать это
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("My Title");
builder.setMessage("your message");
builder.setPositiveButton("OK", null);
AlertDialog dialog = builder.show();
TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
dialog.show();
Я знаю, эта нить старый, но может помочь некоторым людям: D
TextView title = new TextView(this);
title.setText("Client details not saved!");
title.setPadding(10, 10, 10, 10);
title.setGravity(Gravity.CENTER);
// title.setTextColor(getResources().getColor(R.color.greenBG));
title.setTextSize(23);
TextView msg = new TextView(this);
msg.setText("You're going to lose all the information if you continue!");
msg.setPadding(10, 10, 10, 10);
msg.setGravity(Gravity.CENTER);
msg.setTextSize(18);
DialogInterface.OnClickListener onClick = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
finish();
}
}
};
Builder builder = new AlertDialog.Builder(this);
builder.setCustomTitle(title);
builder.setView(msg);
builder.setCancelable(true);
builder.setPositiveButton("Yes", onClick);
builder.setNegativeButton("No", onClick);
AlertDialog dialog = builder.create();
dialog.show();
. Можете ли вы написать, как ваш код полезен и отличается от других ответов. Это поможет людям прочитать ваш ответ и определить, попробовать ли это или нет (и может помочь им учиться) – Patrick
Как вы добавляете текстовый текст 'title' тоже в' builder'? –
Попробуйте - это будет делать трюк.
AlertDialog.Builder completeDialog = new AlertDialog.Builder(Main.this);
TextView resultMessage = new TextView(Main.this);
resultMessage.setTextSize(22);
resultMessage.setText("Upload completed!");
resultMessage.setGravity(Gravity.CENTER);
completeDialog.setView(resultMessage);
completeDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@SuppressLint("DefaultLocale")
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
completeDialog.show();
Лучшим способом является создание пользовательского диалогового окна.
view_dialog_box.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#A9E2F3">
<TextView
android:id="@+id/txtDiaTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connection Alart"
android:textColor="@color/Black"
android:textStyle="bold"
android:gravity="center"
android:padding="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<View
android:layout_width="match_parent"
android:layout_height="1dip"
android:background="#2E9AFE"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
/>
<TextView
android:id="@+id/txtDiaMsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dp"
android:text="No Internet Connection"
android:textColor="@color/Black" />
<Button
android:id="@+id/btnOk"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="OK"
android:textColor="@color/Black"
android:textStyle="bold"
android:padding="5dp"
android:layout_margin="5dp"
android:background="@color/White"/>
Затем использовать в Java файл
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.view_dialog_box);
// set the custom dialog components - text and button
TextView text = (TextView) dialog.findViewById(R.id.txtDiaTitle);
TextView image = (TextView) dialog.findViewById(R.id.txtDiaMsg);
Button dialogButton = (Button) dialog.findViewById(R.id.btnOk);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
Вы можете использовать свой собственный макет для оповещения о диалоговом макете. Для выравнивания по умолчанию оповещения диалогового расположения центра сообщений вы можете сделать
AlertDialog alertDialog;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("hello world");
alertDialog = builder.show();
TextView messageText = (TextView) alertDialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
Будьте осторожны, если вы установите MessageText с findViewById перед вызовом builder.show() вы получите исключения нулевого указателя.
Просто используйте этот метод и ваш диалог заголовок и сообщение появится в центре:
государственной статической силы OpenDialog (Context контекст, строка сообщения) {
TextView title = new TextView(context);
// You Can Customise your Title here
title.setText("Information Message");
title.setBackgroundColor(Color.BLACK);
title.setPadding(10, 15, 15, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.WHITE);
title.setTextSize(22);
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setCustomTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
// You Can Customise your Message here
TextView messageView = (TextView) alertDialog
.findViewById(android.R.id.message);
messageView.setGravity(Gravity.CENTER);
}
- 1. центр сообщение по умолчанию AlertDialog в Android
- 2. Android AlertDialog не показывает радиокнопки или сообщение
- 3. Показать длинное сообщение в AlertDialog
- 4. Как изменить AlertDialog (Android)?
- 5. Как закрыть AlertDialog в android
- 6. Как обернуть alertdialog в android?
- 7. Как вызвать alertDialog в alertDialog?
- 8. Android AlertDialog: TYPE_SYSTEM_ALERT
- 9. Ошибка AlertDialog в android
- 10. Android TabActivity в AlertDialog
- 11. Android Listview в alertDialog
- 12. Android - Гиперссылка в AlertDialog
- 13. Настроить AlertDialog в Android
- 14. Грубое поведение AlertDialog в android
- 15. Отключить (положительное) сообщение AlertDialog по умолчанию
- 16. обновления или изменить AlertDialog сообщение
- 17. AlertDialog на Android IOException
- 18. Android AlertDialog и PreferenceActivity
- 19. Как установить тему в AlertDialog на Android
- 20. Android CountDownTimer и AlertDialog
- 21. как повторно использовать android alertdialog
- 22. Android AlertDialog как передать args
- 23. Как выровнять TextView в android
- 24. Как выровнять кнопки в Android
- 25. Как выровнять вид в Android
- 26. Как выровнять текст в android
- 27. Как проверить AlertDialog на Android?
- 28. AlertDialog Название и сообщение устанавливается в центре
- 29. Как добавить изображения в AlertDialog в android?
- 30. android как выровнять кнопки?
Как сделать то же самое с AlertDialog? –