Ответ 1
Я решил проблему, используя тему DialogFragment.STYLE_NO_TITLE, а затем подделал строку заголовка в макете диалога.
Мне интересно, как можно избавиться от (или изменить цвет) titleDivider в диалоге. Это синяя линия под заголовком диалога, показанная на устройствах сотовой связи +.
Я предполагаю, что это соответствующий фрагмент макета из SDK, но поскольку атрибут стиля отсутствует, я не знаю, как его стилизовать. Если я попытаюсь найти findViewById, не будет android.R.id.titleDivider
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:fitsSystemWindows="true">
<TextView android:id="@android:id/title" style="?android:attr/windowTitleStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="@android:dimen/alert_dialog_title_height"
android:paddingLeft="16dip"
android:paddingRight="16dip"
android:gravity="center_vertical|left" />
<View android:id="@+id/titleDivider"
android:layout_width="match_parent"
android:layout_height="2dip"
android:background="@android:color/holo_blue_light" />
<FrameLayout
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:foreground="?android:attr/windowContentOverlay">
<FrameLayout android:id="@android:id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
Я попытался переопределить dialogTitleDecorLayout, который является ссылкой только на dialog_title_holo.xml в моем theme.xml, но безуспешно. Ошибка:
error: Ошибка: ресурс не найден, который соответствует указанному имени: attr 'DialogTitleDecorLayout'.
Я решил проблему, используя тему DialogFragment.STYLE_NO_TITLE, а затем подделал строку заголовка в макете диалога.
Спасибо. Все, но я получил решение, чтобы получить ссылку на titedivider из alertdialog, чтобы изменить его цвет, используя нижеприведенный код. Надеюсь, это поможет кому-то.
int divierId = dialog.getContext().getResources()
.getIdentifier("android:id/titleDivider", null, null);
View divider = dialog.findViewById(divierId);
divider.setBackgroundColor(getResources().getColor(R.color.creamcolor));
Вам нужно реализовать
myDialog = builder.create();
myDialog.setOnShowListener(new OnShowListenerMultiple());
//----------------------------
//Function to change the color of title and divider of AlertDialog
public static class OnShowListenerMultiple implements DialogInterface.OnShowListener {
@Override
public void onShow( DialogInterface dialog ) {
if( !(dialog instanceof Dialog) )
return;
Dialog d = ((Dialog) dialog);
final Resources resources = d.getContext().getResources();
final int color = AppUtility.getColor( resources, R.color.defaultColor );
try {
int titleId = resources.getIdentifier( "android:id/alertTitle", null, null );
TextView titleView = d.findViewById( titleId );
titleView.setTextColor( color );
}
catch( Exception e ) {
Log.e( "XXXXXX", "alertTitle could not change color" );
}
try {
int divierId = resources.getIdentifier( "android:id/titleDivider", null, null );
View divider = d.findViewById( divierId );
divider.setBackgroundColor( color );
}
catch( Exception e ) {
Log.e( "XXXXXX", "titleDivider could not change color" );
}
}
}
Вот как я решил, что (спасибо http://joerg-richter.fuyosoft.com/?p=181):
MyDialogBuilder.class
public class MyDialogBuilder extends android.app.AlertDialog.Builder {
public MyDialogBuilder(Context context) {
super(context);
}
@NonNull
@Override
public android.app.AlertDialog create() {
final android.app.AlertDialog alertDialog = super.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
int titleDividerId = getContext().getResources()
.getIdentifier("titleDivider", "id", "android");
View titleDivider = alertDialog.findViewById(titleDividerId);
if (titleDivider != null) {
titleDivider.setBackgroundColor(getContext().getResources()
.getColor(R.color.alert_dialog_divider));
}
}
});
return alertDialog;
}
}
использование
<View android:id="@+id/titleDivider"
android:layout_width="match_parent"
android:layout_height="2dip"
android:background=#CC3232 />
Перед записью dialog.show()
напишите:
int divierId = dialog.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
View divider = dialog.findViewById(divierId);
if(divider!=null){
divider.setBackgroundColor(getResources().getColor(R.color.transparent));}
В colors.xml:
<color name="transparent">#00000000</color>
Если вы не хотите использовать стиль по умолчанию, не используйте AlertDialog. Вы можете пойти с Activity (с вашим настраиваемым макетом) с помощью диалогового окна.
<activity android:theme="@android:style/Theme.Dialog">
Этот тест тестируется на некоторых устройствах 4.x:
TextView title = (TextView)getWindow().getDecorView().findViewById(android.R.id.title);
((ViewGroup)title.getParent()).getChildAt(1).setVisibility(View.GONE);
Ваша идея была верна. Однако dialogTitleDecorLayout, который вы искали, является частным ресурсом, поэтому вы не можете получить доступ к нему обычным способом. Но вы все равно можете получить к нему доступ с помощью синтаксиса:
<item name="*android:dialogTitleDecorLayout">@layout/dialog_title</item>
Добавление этого в мой собственный стиль и просто копирование dialog_title.xml в мое приложение и его изменение немного решили проблему в моем случае.
Вы смотрите этот, и для этого есть pcecial библиотека, вы можете смотреть его там. И последняя ссылка решит вашу проблему.
Это никоим образом не скрывает контроль над бротой. У меня была та же проблема. единственное, что вы можете сделать, это создать свой собственный CustomDialog
Загрузите и посмотрите на шаблон дизайна, тогда это будет легко
Вот одно учебное пособие О создании пользовательского диалога
Важная часть после создания DialogObject не задает Title by setTitle() создайте TextView внутри своего CustomLayout и вызовите его из findViewByID() и установите заголовок
вы можете создать собственное диалоговое окно, подобное этому:
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog);
Button okay = (Button) dialog.findViewById(R.id.button1);
okay.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// do your work
}
});
Задайте настраиваемый заголовок в макете, не используйте android
dialog.setTitle();
и ваш custom_dialog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:textSize="40sp"
android:text="Hello"/>
<Button
android:id="@+id/button1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="150dp"
android:text="OK" />
</RelativeLayout>
"Удаление синей линии", если я правильно предполагаю, означает падение границы между заголовком диалогового окна и его телом. Эта граница исходит из темы Holo, поэтому ее невозможно отбросить без использования пользовательского макета.
Создайте файл с именем custom-dialog.xml со следующим содержимым (это просто пример..модифицируйте его как хотите):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/general_dialog_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/dialogTopImage"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.12"
android:padding="10dp" />
<LinearLayout
android:id="@+id/dialogLine"
android:layout_width="fill_parent"
android:layout_height="3dp"
android:background="@drawable/green_btn"
android:orientation="vertical" />
<TextView
android:id="@+id/dialogText"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.32"
android:padding="5dp"
android:text=""
/>
<LinearLayout
android:id="@+id/general_dialog_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_marginBottom="5dp"
android:layout_weight="0.11"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="@+id/dialogButton"
android:layout_width="100dp"
android:textSize="8pt"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:background="@drawable/green_btn"
android:gravity="center"
android:text="Ok" />
</LinearLayout>
Как вы видите, я использую ресурсы и прочее, которых не будет в вашем проекте, но вы можете безопасно их удалить. Результат в моем случае более или менее следующий: с изображением сверху, которое я запрограммировал в коде.
Чтобы создать диалог, используйте что-то вроде:
private Dialog createAndShowCustomDialog(String message, Boolean positive, Drawable d, View.OnClickListener cl, String text1) {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.general_dialog_layout);
// BIND
ImageView image = (ImageView) dialog.findViewById(R.id.dialogTopImage);
TextView text = (TextView) dialog.findViewById(R.id.dialogText);
Button button = (Button) dialog.findViewById(R.id.dialogButton);
LinearLayout line = (LinearLayout) dialog.findViewById(R.id.dialogLine);
// SET WIDTH AND HEIGHT
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = (int) (displaymetrics.widthPixels * 0.85);
int height = (int) (displaymetrics.heightPixels * 0.60);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.width = width;
dialog.getWindow().setLayout(width, height);
// SET TEXTS
text.setText(message);
button.setText(text1);
// SET IMAGE
if (d == null) {
image.setImageDrawable(getResources().getDrawable(R.drawable.font_error_red));
} else {
image.setImageDrawable(d);
}
// SET ACTION
if (cl == null) {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
} else {
button.setOnClickListener(cl);
}
// SHOW
dialog.show();
return dialog;
}
В цветах .xml:
<color name="transparent">#00000000</color>
В диалоговом окне:
int divierId = dialog.getContext(). getResources(). getIdentifier ( "android: id/titleDivider", null, null);
Просмотреть divider = d.findViewById(divierId); divider.setBackgroundColor(GetResources() GetColor (R.color.transparent).);
Чтобы полностью скрыть синюю линию по умолчанию (если вы находитесь в DialogFragment
):
Dialog dialog = getDialog();
if (dialog != null) {
final int dividerId = dialog.getContext().getResources()
.getIdentifier("android:id/titleDivider", null, null);
View divider = dialog.findViewById(dividerId);
if (divider != null) {
divider.setBackground(null);
}
}
int divierId = dialog.getContext().getResources()
.getIdentifier("android:id/titleDivider", null, null);
View divider = dialog.findViewById(divierId);
divider.setVisibility(View.INVISIBLE);