Подтвердить что ты не робот

Android: AlertDialog с пользовательским представлением и закругленными углами

Я пытаюсь создать AlertDialog с пользовательским view (без заголовка или нижнего колонтитула) и закругленными углами. Я видел много сообщений о том, как это сделать, и я много пробовал, но я не могу построить его, как я хочу.

Это моя цель:

enter image description here

Я создал drawable для dialog, называемого dialog_background.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid
        android:color="#FFAAAAAA" />

    <stroke
        android:width="2dp"
        android:color="#FF000000" />

    <corners android:radius="20dp" />
</shape>

И я добавил style, чтобы использовать его:

<style name="MyDialog" parent="@android:style/Theme.Dialog">
    <item name="android:background">@drawable/dialog_background</item>
</style>

layout layout будет иметь две кнопки. Сейчас я покажу вам пустой LinearLayout, чтобы сделать его простым. Это playdialog.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    style="@style/MyDialog"
     >

</LinearLayout>

Чтобы построить dialog, я использую DialogFragment. Это его функция onCreateDialog:

public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();

    builder.setView(inflater.inflate(R.layout.playdialog, null));
    return builder.create();
}

Хорошо, если я использую такой код, я получаю следующее:

enter image description here

Я попытался установить фон dialog прозрачным, изменив код DialogFragment:

public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();

    builder.setView(inflater.inflate(R.layout.playdialog, null));

    **NEW**        

    Dialog d = builder.create();
    d.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    return d; 
}

Результат точно такой же, поэтому я понял, что этот белый прямоугольник под моим dialog является из моего пользовательского view, а не из dialog. Я уже устанавливаю свой фон view в dialog_background.xml, поэтому я не могу установить его прозрачно или потерять углы, цвет и т.д.

Затем я решил изменить фон dialog, используя dialog_background.xml, и мое представление имеет сплошной цвет в качестве фона.

В моем пользовательском view layout (playdialog.xml) я заменил style = "@style/MyDialog" на:

android:background="#FFAAAAAA"

И затем в моем DialogFragment я использовал этот код:

public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();

    builder.setView(inflater.inflate(R.layout.playdialog, null));

    **NEW**        

    Dialog d = builder.create();
    d.getWindow().setBackgroundDrawableResource(R.drawable.dialog_background);
    return d; 
}

Это то, что я получаю:

enter image description here

Это почти то, что я хотел, но вы можете видеть мои пользовательские границы view, поэтому он недостаточно хорош. В этот момент я не знал, что еще я могу сделать.

Кто-нибудь знает, как я могу его решить?

Спасибо!

4b9b3361

Ответ 1

Я только что создал настраиваемый диалог оповещений. Но его углы не закруглены.

Сначала создайте макет для него как -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="240sp"
android:layout_height="wrap_content"
android:background="#FFFFFF"
tools:ignore="SelectableText" >

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="1sp"
    tools:ignore="UselessParent" >

    <TableLayout 
        android:id="@+id/tablelayout_dialog_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:stretchColumns="1" >

        <TableRow
            android:id="@+id/tablerow_dialog_title"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"            
            tools:ignore="UselessParent" >

            <ImageView 
                android:id="@+id/imageview_dialog_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/alertwhite" 
                android:layout_gravity="center"
                android:background="#643c3a"
                android:contentDescription="@string/string_todo"/>

            <TextView
                android:id="@+id/textview_dialog_title"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent" 
                android:background="#643c3a"
                android:padding="10sp"
                android:gravity="center_vertical"
                android:textColor="#FFFFFF"
                android:textSize="15sp" />

        </TableRow>     
    </TableLayout>

    <View 
        android:id="@+id/viewline_dialog"
        android:layout_below="@+id/tablelayout_dialog_title"
        android:layout_width = "wrap_content" 
        android:layout_height="0.25dip"
        android:background="#ffffff"          
        android:layout_centerVertical ="true" />

    <TextView
        android:id="@+id/textview_dialog_text"
        android:layout_below="@+id/viewline_dialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="8sp"
        android:background="#643c3a"
        android:textColor="#FFFFFF"
        android:textSize="12sp" />

    <View 
        android:id="@+id/viewline1_dialog"
        android:layout_width = "wrap_content" 
        android:layout_height="0.5dip"
        android:background="#ffffff"          
        android:layout_centerVertical ="true" 
        android:layout_below="@+id/textview_dialog_text"/>

    <TableLayout 
        android:id="@+id/tablelayout_dialog_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:stretchColumns="*"
        android:layout_below="@+id/viewline1_dialog"
        android:background="#a8a8a8" >

        <TableRow
            android:id="@+id/tablerow_dialog_button"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"            
            tools:ignore="UselessParent" >

            <Button
                android:id="@+id/button_dialog_yes"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="8sp"
                android:paddingTop="5sp"
                android:paddingBottom="5sp"
                android:background="@drawable/roundedcornerbuttonfordialog_shape"
                android:text="@string/string_yes" />

            <Button
                android:id="@+id/button_dialog_no"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="8sp"
                android:paddingTop="5sp"
                android:paddingBottom="5sp"
                android:background="@drawable/roundedcornerbuttonfordialog_shape"
                android:text="@string/string_no" />

        </TableRow>
    </TableLayout>

</RelativeLayout>

Теперь напишите код диалога как -

public static void callAlert(String message, final Context context){
    final Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.customdialog_layout);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));               

    TextView tvTitle = (TextView) dialog.findViewById(R.id.textview_dialog_title);
    tvTitle.setText("MyApp..");

    TextView tvText = (TextView) dialog.findViewById(R.id.textview_dialog_text);
    tvText.setText(message);    

    Button buttonDialogYes = (Button) dialog.findViewById(R.id.button_dialog_yes);
    buttonDialogYes.setOnClickListener(new OnClickListener() {          
        public void onClick(View v) {
            // Do your stuff...
            dialog.dismiss();
        }
    });

    Button buttonDialogNo = (Button) dialog.findViewById(R.id.button_dialog_no);
    buttonDialogNo.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // Do your stuff...
            dialog.dismiss();
        }           
    });
    dialog.show();
}

И вызовите этот метод как -

String message = "Your Message";
callAlert(message, callingClass.this);

Надеюсь, это поможет вам.

Ответ 2

В моем случае для удаления границ в диалоговом окне это решение было полезным:

dialog.setStyle(DialogFragment.STYLE_NO_FRAME, 0);

как описано здесь fooobar.com/questions/328746/...

Ответ 3

Ниже приведен код проблемы

MyDialog mydialog = new MyDialog(this, "for testing",
            new myOnClickListener() {

                @Override
                public void onPositiveButtonClick() {
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(),
                            "I am positive button in the dialog",
                            Toast.LENGTH_LONG).show();
                }

                @Override
                public void onNegativeButtonClick() {
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(),
                            "I am negative button in the dialog",
                            Toast.LENGTH_LONG).show();
                }
            });

    // this will remove rectangle frame around the Dialog
    mydialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    mydialog.show();

Спасибо, Nagendra

Ответ 4

почему бы вам не использовать изображение, которое вы показываете как "Это моя цель:" сохранить изображение цели в bg в папке с возможностью переноса.

private AlertDialog createAlertDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(getLayoutInflater().inflate(R.layout.playdialog, null));
    return builder.create();
}  

затем

AlertDialog dialog = createAlertDialog();
dialog.show();