Как изменить цвет заголовка AlertDialog и цвет линии под ним
Я изменил цвет заголовка AlertDialog с помощью этой команды
alert.setTitle( Html.fromHtml("<font color='#FF7F27'>Set IP Address</font>"));
Но я хочу изменить цвет строки, которая появляется под заголовком; Как мне это сделать?
Примечание. Я не хочу использовать настраиваемый макет
![screenshot of the desired effect]()
Ответы
Ответ 1
К сожалению, это не очень простая задача. В моем ответе здесь, я подробно расскажу, как настроить цвет ListSeparator
, просто проверив родительский стиль, используемый Android, создав новое изображение и создав новый стиль, основанный на оригинале. К сожалению, в отличие от стиля ListSeparator
, темы AlertDialog
являются внутренними и поэтому не могут быть указаны как родительские стили. Нет простого способа изменить эту маленькую синюю линию! Таким образом, вам нужно прибегнуть к созданию настраиваемых диалогов.
Если это просто не твоя чашка чая... не сдавайся! Меня очень беспокоило, что не было простого способа сделать это, поэтому я создал небольшой проект по github для создания быстро настраиваемых голографических диалоговых окон (при условии, что телефон поддерживает стиль Holo). Здесь вы можете найти проект: https://github.com/danoz73/QustomDialog
Он должен легко разрешить переход от скучного синего к захватывающему апельсину!
![enter image description here]()
Проект в основном является примером использования настраиваемого диалогового построителя, и в этом примере я создал настраиваемое представление, которое, как представляется, соответствует примеру IP-адреса, который вы задаете в исходном вопросе.
С помощью QustomDialog
, чтобы создать базовое диалоговое окно (заголовок, сообщение) с желаемым разным цветом для заголовка или разделителя, вы используете следующий код:
private String HALLOWEEN_ORANGE = "#FF7F27";
QustomDialogBuilder qustomDialogBuilder = new QustomDialogBuilder(v.getContext()).
setTitle("Set IP Address").
setTitleColor(HALLOWEEN_ORANGE).
setDividerColor(HALLOWEEN_ORANGE).
setMessage("You are now entering the 10th dimension.");
qustomDialogBuilder.show();
И чтобы добавить пользовательский макет (например, чтобы добавить небольшой IP-адрес EditText
), вы добавляете
setCustomView(R.layout.example_ip_address_layout, v.getContext())
строителю с макетом, который вы разработали (пример IP можно найти в github). Надеюсь, это поможет. Большое спасибо Джозефу Эрлу и его ответу здесь.
Ответ 2
Цвет разделителя:
Это взломать немного, но он отлично работает для меня, и он работает без какой-либо внешней библиотеки (по крайней мере, на Android 4.4).
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.dialog)
.setIcon(R.drawable.ic)
.setMessage(R.string.dialog_msg);
//The tricky part
Dialog d = builder.show();
int dividerId = d.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
View divider = d.findViewById(dividerId);
divider.setBackgroundColor(getResources().getColor(R.color.my_color));
В диалоговом окне alert_dialog.xml можно найти дополнительные диалоговые окна. Например. android:id/alertTitle
для изменения цвета заголовка...
ОБНОВЛЕНИЕ: цвет заголовка
Взлом для изменения цвета заголовка:
int textViewId = d.getContext().getResources().getIdentifier("android:id/alertTitle", null, null);
TextView tv = (TextView) d.findViewById(textViewId);
tv.setTextColor(getResources().getColor(R.color.my_color));
Ответ 3
проверьте, что это полезно для вас...
public void setCustomTitle (View customTitleView)
вы получите подробную информацию по следующей ссылке.
http://developer.android.com/reference/android/app/AlertDialog.Builder.html#setCustomTitle%28android.view.View%29
CustomDialog.java
Dialog alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(R.layout.title);
TextView msg = (TextView)alert.findViewById(R.id.textView1);
msg.setText("Hello Friends.\nIP address : 111.111.1.111");
alert.show();
title.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set IP address"
android:textColor="#ff0000"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_marginTop="5dp"
android:background="#00ff00"
/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#775500"
android:textAppearance="?android:attr/textAppearanceLarge" />
![enter image description here]()
Ответ 4
Это установит цвет для названия, значка и разделителя. Связано с новой версией Android.
public static void colorAlertDialogTitle(AlertDialog dialog, int color) {
int dividerId = dialog.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
if (dividerId != 0) {
View divider = dialog.findViewById(dividerId);
divider.setBackgroundColor(color);
}
int textViewId = dialog.getContext().getResources().getIdentifier("android:id/alertTitle", null, null);
if (textViewId != 0) {
TextView tv = (TextView) dialog.findViewById(textViewId);
tv.setTextColor(color);
}
int iconId = dialog.getContext().getResources().getIdentifier("android:id/icon", null, null);
if (iconId != 0) {
ImageView icon = (ImageView) dialog.findViewById(iconId);
icon.setColorFilter(color);
}
}
Не забудьте вызвать dialog.show() перед вызовом этого метода.
Ответ 5
Следуя Диалоговому исходному коду, я обнаружил, что Заголовок генерируется в классе MidWindow
, раздувая макет dialog_title_holo.xml
. поэтому Id mTitleView
равен title
, а Id делителя titleDivider
.
мы можем получить доступ к Id title
просто android.R.id.title
.
и доступ к Id titleDivider
на Resources.getSystem().getIdentifier("titleDivider","id", "android");
Последний код, который я использовал для изменения направления заголовка и изменения цвета:
TextView mTitle = (TextView)findViewById(android.R.id.title);
mTitle.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
int x = Resources.getSystem().getIdentifier("titleDivider","id", "android");
View titleDivider = findViewById(x);
titleDivider.setBackgroundColor(getContext().getResources().getColor(R.color.some_color));
Ответ 6
Если вам не нужна "библиотека" для этого, вы можете использовать этот плохо взломать:
((ViewGroup)((ViewGroup)getDialog().getWindow().getDecorView()).getChildAt(0)) //ie LinearLayout containing all the dialog (title, titleDivider, content)
.getChildAt(1) // ie the view titleDivider
.setBackgroundColor(getResources().getColor(R.color.yourBeautifulColor));
Это было протестировано и работало над 4.x; не проверено, но если моя память хорошая, то она должна работать для 2.x и 3.x
Ответ 7
Если вы создаете настраиваемый диалог "Макет для предупреждений"
то вы можете легко добавить такой способ, чтобы изменить цвет
<LinearLayout
android:id="@+id/DialogTitleBorder"
android:layout_width="fill_parent"
android:layout_height="1dip"
android:layout_below="@id/mExitDialogDesc"
android:background="#4BBAE3" <!--change color easily -->
>
</LinearLayout>
Ответ 8
Если вы используете собственный макет заголовка, вы можете использовать его как alertDialog.setCustomTitle(customTitle);
Например
on UI thread used dialog like
LayoutInflater inflater=LayoutInflater.from(getApplicationContext());
View customTitle=inflater.inflate(R.layout.customtitlebar, null);
AlertDialog.Builder d=new AlertDialog.Builder(this);
d.setCustomTitle(customTitle);
d.setMessage("Message");
d.setNeutralButton("OK", null);
d.show();
customtitlebar.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#525f67">
<ImageView
android:id="@+id/icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/ic_launcher"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" >
</ImageView>
<TextView
android:id="@+id/customtitlebar"
android:layout_width="match_parent"
android:layout_height="40dp"
android:textColor="#ffffff"
android:text="Title Name"
android:padding="3px"
android:textStyle="bold"
android:layout_toRightOf="@id/icon"
android:layout_alignParentTop="true"
android:gravity="center_vertical"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#ff0000"
android:layout_below="@id/icon"><!-- This is line below the title -->
</ImageView>
</RelativeLayout>
Ответ 9
Если вы используете расширение диалога, используйте:
requestWindowFeature (Window.FEATURE_NO_TITLE);
Ответ 10
Продолжая этот ответ: fooobar.com/questions/58809/..., я разыграл хороший репортаж github от @daniel-smith и сделал некоторые улучшения:
- улучшенный пример Activity
- улучшенные макеты
- фиксированный метод
setItems
- добавлены разделители на
items_list
- отменить диалоги при нажатии
- поддержка отключенных элементов в методах
setItems
-
listItem
сенсорная обратная связь
- прокручиваемое диалоговое сообщение
ссылка: https://github.com/dentex/QustomDialog
Ответ 11
Я придумал другое решение, которое обрабатывает стиль ваших диалогов в одном месте, и вам не нужно беспокоиться о том, когда вы его применяете - диалог показывается/не показан, что может вызвать ошибку (нужно вызвать requestFocus или что-то еще например, P).
Пример использования:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
AlertDialog dialog = builder.create(); //or builder.show()
DialogViewDecorator.decorate(dialog, android.R.color.holo_red_light); //can also set the defaut color in the class
Реализация:
public class DialogViewDecorator {
private static final
@ColorRes int DEFAULT_TITLE_DIVIDER_COLOR = android.R.color.holo_orange_light;
public static void decorate(Dialog dialog) {
decorate(dialog, DEFAULT_TITLE_DIVIDER_COLOR);
}
/**
* Sets the title divider color when the view is shown by setting DialogInterface.OnShowListener on the dialog.
* <p/>
* If you want to do other things onShow be sure to extend OnDecoratedDialogShownListener(call super.show(...)!)
* and call {@link #decorate(Dialog, int, OnDecoratedDialogShownListener)}.
*
* @param dialog
* @param titleDividerColor
*/
public static void decorate(Dialog dialog, final int titleDividerColor) {
decorate(dialog, titleDividerColor, new OnDecoratedDialogShownListener(titleDividerColor));
}
/**
* Method for setting a extended implementation of OnDecoratedDialogShownListener. Don't forget to call super
* or the titleDividerColor wont be applied!
*
* @param dialog
* @param titleDividerColor
* @param OnShowListener
* @param <T>
*/
public static <T extends OnDecoratedDialogShownListener> void decorate(Dialog dialog, int titleDividerColor, T OnShowListener) {
if (dialog == null || titleDividerColor <= 0) { return; }
if (dialog.isShowing()) {
setTitleDividerColor(dialog, titleDividerColor);
} else {
dialog.setOnShowListener(OnShowListener);
}
}
private static void setTitleDividerColor(DialogInterface dialogInterface, int titleDividerColor) {
try {
Dialog dialog = (Dialog) dialogInterface;
int dividerId = dialog.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
View divider = dialog.findViewById(dividerId);
if (divider != null) {
divider.setBackgroundColor(dialog.getContext().getResources().getColor(titleDividerColor));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static class OnDecoratedDialogShownListener implements DialogInterface.OnShowListener {
private int titleDividerColor;
public OnDecoratedDialogShownListener() {
this.titleDividerColor = DEFAULT_TITLE_DIVIDER_COLOR;
}
public OnDecoratedDialogShownListener(int titleDividerColor) {
this.titleDividerColor = titleDividerColor;
}
@Override
public void onShow(DialogInterface dialogInterface) {
setTitleDividerColor(dialogInterface, titleDividerColor);
}
}}
Ответ 12
В классе onCreateView я помещаю это:
Dialog d = getDialog();
d.setTitle(Html.fromHtml("<font color='#EC407A'>About</font>"));
int dividerId = d.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
View divider = d.findViewById(dividerId);
divider.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
colorПримечательные ссылки на наш файл colors.xml, в котором хранятся все цвета. Кроме того, d.setTitle
предоставляет хакерский способ установить цвет заголовка.