Сломанный макет диалога Android, как исправить?

#android #android-layout #dialog

#Android #android-layout #диалог

Вопрос:

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

В любом случае, это решение не удалось за пределами эмулятора.

Похоже, что Android присваивает диалоговому окну фиксированную высоту, и если мой пользовательский заголовок поглотил слишком большую часть этой высоты, сжимая все остальное. Правильно ли это и как мне это исправить? Проблема введите описание изображения здесь

 public class GetUserNameDialogFragment extends DialogFragment {

    final String TAG = "GetUserNameDialog";
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogStyle);
        //TODO getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);

        LayoutInflater inflater = getActivity().getLayoutInflater();
        final View sunburst =inflater.inflate(R.layout.dialog_user_name, null);
        builder.setView(sunburst);


        builder.setCancelable(false)
                .setPositiveButton("Let's go!", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        Log.wtf(TAG, "button press");
                        EditText name = (EditText) sunburst.findViewById(R.id.nameEditText);
                        String userName = name.getText().toString().trim();
                        //TODO needs to be validated
                        SharedPreferences sharedPref = getActivity().getSharedPreferences("userDetails", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPref.edit();
                        editor.putString("userName", userName );
                        editor.commit();
                    }
                });
        // Create the AlertDialog object and return it
        return builder.create();
    }
}
  

Вот xml

     <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:adjustViewBounds="true"
        app:srcCompat="@drawable/ic_ball_sunburst_classic"
        android:background="@color/colorAccent"
        />
    <LinearLayout
        android:layout_width="250dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:layout_height="125dp">
    <EditText
        android:id="@ id/nameEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="8dp"
        android:hint="Enter your first name"/>
    </LinearLayout>
</LinearLayout>
  

Вся помощь очень ценится, первое впечатление от моего приложения — какая катастрофа!

Ответ №1:

Почему вы не используете Dialog вместо AlertDialog ?

Я построил пример с использованием диалогового окна, и он отлично работает

введите описание изображения здесь

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
android:layout_width=" 290dp"
android:layout_height="wrap_content"
android:background="#4CAF50">


<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true"
    android:src="@drawable/base"
    android:background="@color/colorAccent"
    />

    <EditText
        android:textColor="#fff"
        android:textColorHint="#fff"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:id="@ id/nameEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your first name"/>

<Button
    android:layout_marginRight="10dp"
    android:layout_marginEnd="10dp"
    android:id="@ id/letsGo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right"
    android:text="Let's Go"
    android:textColor="#fff"
    android:background="@android:color/transparent"/>
  

     final Dialog dialog = new Dialog(context);
    if(dialog.getWindow() != null){
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }
    dialog.setContentView(R.layout.dialog);

    Button letsGO = (Button) dialog.findViewById(R.id.letsGo);
    EditText nameEditText = (EditText) dialog.findViewById(R.id.nameEditText);

    letsGO.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(context, "Lets GO!", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        }
    });
    dialog.show();