диалог Android не загружает полные данные - PullRequest
1 голос
/ 04 октября 2019

У меня есть диалоговые окна, открытые на основе imageButtons Я могу открыть свои диалоговые окна для каждого imageButton, но в моих диалоговых окнах не отображаются полные данные.

Ошибка

  1. Кнопки вдиалог не будет отображаться
  2. Мой диалог не имеет фона

Код

Custom dialog

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/dialog_imageview"
        android:layout_width="294dp"
        android:layout_height="246dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_centerInParent="true"
        android:layout_marginStart="68dp"
        android:layout_marginTop="274dp"
        android:layout_marginEnd="69dp"
        android:layout_marginBottom="270dp"
        android:contentDescription="image"
        android:foregroundGravity="center"
        tools:srcCompat="@tools:sample/avatars[0]" />

    <TextView
        android:id="@+id/tv_text"
        android:layout_width="wrap_content"
        android:layout_height="49dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="59dp"
        android:layout_marginTop="474dp"
        android:layout_marginEnd="59dp"
        android:layout_marginBottom="136dp"
        android:gravity="center_vertical"
        android:text="TextView"
        android:textAlignment="center"
        android:textSize="30sp" />

    <Button
        android:id="@+id/close_btn"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="285dp"
        android:layout_marginTop="680dp"
        android:layout_marginEnd="59dp"
        android:layout_marginBottom="193dp"
        android:background="#F50057"
        android:gravity="center"
        android:text="Close"
        android:textAlignment="center"
        android:textColor="#FFFFFF" />

    <Button
        android:id="@+id/play_btn"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="59dp"
        android:layout_marginTop="680dp"
        android:layout_marginEnd="289dp"
        android:layout_marginBottom="190dp"
        android:background="#00E676"
        android:gravity="center"
        android:text="Play"
        android:textAlignment="center" />
</RelativeLayout>

Activity function

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_buildings)

        // open dialog1
        val imageButton1 = this.findViewById(R.id.imageButton1) as ImageButton;
        imageButton1.setOnClickListener() {
            val dialog = Dialog(context, android.R.style.Theme_Translucent_NoTitleBar)
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
            dialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
            dialog.getWindow().setGravity(Gravity.CENTER)
            dialog.setContentView(R.layout.dialog_custom)

            val tv_text = dialog.findViewById(R.id.tv_text)as TextView
            val btn_close = dialog.findViewById(R.id.close_btn) as Button
            val btn_play = dialog.findViewById(R.id.play_btn) as Button
            val imageView = dialog.findViewById(R.id.dialog_imageview) as ImageView

            imageView.setImageResource(R.drawable.school) //set image here
            tv_text.setText("School")  // set description here


            //insert your button function here
            btn_close.setOnClickListener {
                fun onClick(v: View) {
                    dialog.dismiss()
                }
            }

            btn_play.setOnClickListener {
                fun onClick(v: View) {
                    val mp: MediaPlayer? = MediaPlayer.create(this, R.raw.a)
                    mp?.start();
                }
            }

            dialog.show();
        }
}

Снимок экрана

one

Есть идеи?

1 Ответ

0 голосов
/ 04 октября 2019

Разные телефоны получили разные размеры экрана , в вашем макете вы используете фиксированный размер для вашего вида (фиксированный размер, например, android:layout_marginTop="474dp"), и в результате получается, что на одном экране может выглядеть хорошо (Экран предварительного просмотра вашей студии Android) не будет хорошо смотреться на другом экране (ваш телефон).

Как это можно исправить - вы можете использовать ConstraintLayout , чтобы ваш экран реагировал на все размеры экрана.

Возьмем такой макет, например:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent">


<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:text="Button"
    app:layout_constraintHeight_percent="0.1"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/guideline" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:text="Button"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHeight_percent="0.1"
    app:layout_constraintTop_toTopOf="@+id/guideline" />

<ImageView
    android:id="@+id/imageView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:scaleType="fitXY"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHeight_percent="0.4"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:srcCompat="@tools:sample/avatars[6]" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="Your text here"
    app:layout_constraintBottom_toTopOf="@+id/guideline"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/imageView" />

<android.support.constraint.Guideline
    android:id="@+id/guideline"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.7" />
</android.support.constraint.ConstraintLayout>

Он будет выглядеть так и будет реагировать на все размеры экрана:

enter image description here


Это будет выглядеть так, как будто вы хотите, чтобы это выглядело, но давайте объясним, что я сделал:

  • Я использовал app:layout_constraintHeight_percent="0.1" на кнопках, чтобы указать, что они равны по высоте 10% размера экрана (не фиксированные размеры).

  • В той же концепции я также использовал app:layout_constraintHeight_percent="0.4", поэтому изображение будет равно 40% размера экрана по высоте.

  • Я также использовал Guidelines , чтобы лучше контролировать положение моих кнопок.

Вы можете найти больше информации о созданииадаптивные макеты в Поддержка разных размеров экрана , Барьеры и, как уже упоминалось выше Рекомендации , а также

С помощью вышеуказанных инструментов вы можете создать отзывчивыйраскладка. Вам не нужно использовать ConstraintLayout, чтобы достичь этого, у вас есть другие варианты, но я считаю, что это самый простой способ создания макетов.

...