Как установить прозрачный фон в качестве настраиваемого диалогового окна в android
Мне нужно сделать свое настраиваемое диалоговое окно прозрачным.
Пример кода:
Dialog dialog;
@Override
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case 1:
AlertDialog.Builder builder = null;
Context mContext = this;
LayoutInflater inflater = ( LayoutInflater ) mContext.getSystemService( LAYOUT_INFLATER_SERVICE );
View layout = inflater.inflate( R.layout.about_page, ( ViewGroup ) findViewById( R.id.about_Root ) );
builder = new AlertDialog.Builder( mContext );
builder.setView( layout );
dialog = builder.create();
break;
}
return dialog;
}
Как установить прозрачное диалоговое окно.
Мой XML-код:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/about_Root"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/alert_page_border"
android:orientation="vertical" >
<TextView
android:id="@+id/about_Title"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:gravity="center"
android:layout_weight="1"
android:textSize="25dip"
android:textColor="@android:color/white"
android:textStyle="bold|italic"
android:text="Welcome" />
</LinearLayout>
Код Alert_page_border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#3b3b3b" />
<stroke
android:width="3dp"
android:color="#ffffff" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
<corners
android:radius="2dp" />
</shape>
Пример скриншота:
![enter image description here]()
Как избежать этого цвета блока.
Ответы
Ответ 1
Используйте диалог вместо AlertDialog
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.splash);
dialog.show();
Ответ 2
Если вы используете API >= 11, вы можете попробовать настроить тему на свой диалог следующим образом:
new AlertDialog.Builder(mContext , android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
Или вы можете попробовать установить прозрачный фон:
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
Ответ 3
Этот ваш вопрос точно описывает мою проблему. Я пробовал каждое решение, которое я наткнулся на этот поток, а также на несколько других потоков. Ничего не получилось. Наконец я наткнулся на этот поток и соответствующий ответ.
Мне пришлось создать собственный класс диалога. Так я и сделал, и это сработало. На самом деле для меня было достаточно следующих стилей:
colors.xml
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="transparent_black">#66000000</color>
</resources>
styles.xml
:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="custom_dialog_theme" parent="@android:style/Theme.Translucent">
<item name="android:windowBackground">@color/transparent_black</item>
<item name="android:windowIsFloating">true</item>
</style>
</resources>
Код класса диалога:
import android.app.Dialog;
import android.content.Context;
import my.app.com.android.R;
public class CustomDialog extends Dialog {
public AddBookCustomDialog(final Context context) {
super(context, R.style.custom_dialog_theme);
this.setContentView(R.layout.add_book_dialog);
}
}
И как я использую этот диалог в коде действия:
CustomDialog customDialog = new CustomDialog(this);
customDialog.show();
Я не знаю, почему мне нужно создать собственный класс, чтобы тема была принята во внимание. Теперь я достиг того, что хотел: прозрачный диалог. Следующий бой - позиционировать положительные и отрицательные кнопки, если я больше не могу использовать удобные методы AlertDialog.Builder
. Надеюсь, мой код поможет вам.
Также обратите внимание на низкое значение альфа - возможно, даже попробуйте его с 00, чтобы убедиться, что ваша конфигурация работает.
Ответ 4
Используйте dialog.getWindow().setBackgroundDrawable(null)
для удаления фона по умолчанию.
Вот документ для справки:
/*** Set the background to a given Drawable, or remove the background. If the
* background has padding, this View padding is set to the background's
* padding. However, when a background is removed, this View padding isn't
* touched. If setting the padding is desired, please use
* {@link #setPadding(int, int, int, int)}.
*
* @param d The Drawable to use as the background, or null to remove the
* background
*/
Ответ 5
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/a"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#00000000">
<!-- Write your LinearLayout code here -->
</RelativeLayout>
Попробуйте этот код.
Ответ 6
Попробуйте это,
layout.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
добавьте код выше после этой строки.
View layout = inflater.inflate( R.layout.about_page, ( ViewGroup ) findViewById( R.id.about_Root ) );
Ответ 7
Просто создайте стиль и примените его к диалоговому окну
<style name="myDialogTheme" parent="@android:style/Theme.Dialog">
<item name="android:windowBackground">@color/Transparent</item>
<item name="android:windowIsFloating">false</item>
<item name="android:windowNoTitle">true</item>
</style>
Затем создайте свой диалог с помощью этой темы;
Dialog myDialog = new Dialog(this,R.style.myDialogTheme) {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about_page);
}
};
Надеюсь, это поможет вам достичь своей цели.
Ответ 8
просто удалите
из Alert_page_border.xml