Изменения фона PopupWindow работают на эмуляторах, но не на физических устройствах - PullRequest
0 голосов
/ 03 мая 2020

Я недавно создал меню в PopupWindow. Это должно позволить пользователям выбирать день и час. Когда пользователь выбирает элемент, фон должен быть изменен на голубой, а текст - на черный. Затем, если пользователь щелкнет снова, фон для этого элемента должен переключиться обратно на белый, а текст - на серый.

Это хорошо работает на эмуляторе. Я проверил это на Nexus 6 и Pixel 3 XL.

Однако на физическом устройстве происходит нечто странное. Когда я нажимаю на элемент, его фон иногда исчезает, показывая активность за ним. В других случаях он мигает на синем фоне или даже меняет фон областей в разных частях экрана. Тем не менее, он иногда работает так, как задумано, с соответствующим изменением фона. Такое поведение наблюдается у меня при тестировании двух телефонов: маленькой Motorola и большой Samsung.

Чтобы решить эту проблему, я пробовал различные решения. Например, я поиграл с основными опциями PopupWindow, такими как setOutsideTouchable и focusable. Я также использовал свой макет, например, устанавливая различные фоны для каждого отдельного элемента и назначая корни во время инфляции. Кроме того, я попытался сделать глобальную переменную для всплывающего окна и сбросить некоторые функции после изменения фона. Однако ни одна из этих попыток не дала никаких результатов. Окно все еще работает, как и ожидалось, на эмуляторе, но не на реальном устройстве.

Любая помощь приветствуется. Ниже приведена ссылка на некоторые скриншоты поведения на физическом устройстве вместе с фрагментами кода. Заранее спасибо.

Снимки экрана: https://imgur.com/a/1K9pSHi

1. Java код для установки всплывающего окна

public void showDurationPopup(View v) {
        LayoutInflater inflater = (LayoutInflater) 
        this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.post_duration_popup,null);
        addDayOpsToViews(inflater,layout);
        addHourOpsToViews(inflater,layout);
        final PopupWindow popup = new PopupWindow(layout, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, false);
        popup.setOutsideTouchable(false);
        popup.update();
        popup.showAtLocation(layout, Gravity.CENTER, 0, 0);
        setPopupFinishBtnListener(layout,popup);
    }
    private void addDayOpsToViews(LayoutInflater inflater,View popupLayout){
        LinearLayout daysListView = popupLayout.findViewById(R.id.daysOpsList);
        View newItem;
        // Set items for days 1-29
        for(int d = 1;d<=29;d++){
            newItem = inflater.inflate(R.layout.duration_item,null);
            TextView contentView = newItem.findViewById(R.id.durItemContent);
            contentView.setText(Integer.toString(d));
            daysListView.addView(newItem);
            setDurItemListener(daysListView,newItem,d-1,0);
        }
        // Load in previously selected pos
        adjustDurItemBackgrounds(daysListView,0);
    }
    private void addHourOpsToViews(LayoutInflater inflater,View popupLayout){
        View newItem;
        LinearLayout hoursListView = popupLayout.findViewById(R.id.hoursOpsList);
        // Set items for hours 0-23
        for(int h = 0;h<=23;h++){
            newItem = inflater.inflate(R.layout.duration_item,null);
            TextView contentView = newItem.findViewById(R.id.durItemContent);
            contentView.setText(Integer.toString(h));
            hoursListView.addView(newItem);
            setDurItemListener(hoursListView,newItem,h,1);
        }
        // Load in previously selected pos
        adjustDurItemBackgrounds(hoursListView,1);
    }

2. Java код ответа onClick

// Set onClickListener for an individual duration item
    // Type 0 is day, type 1 is hour
    private void setDurItemListener(final View listView,
                                    final View newItem, final int position, final int type){
        newItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!(selDurationPos.get(type) == position)) {
                    selDurationPos.set(type, position);
                }
                else{
                    selDurationPos.set(type, -1);
                }
                adjustDurItemBackgrounds((ViewGroup)listView,type);
            }
        });
    }
    private void adjustDurItemBackgrounds(ViewGroup listView,int type){
        int numChildren = listView.getChildCount();
        View currChild;
        for(int c=0; c<numChildren; c++){
            currChild = listView.getChildAt(c);
            if(c==selDurationPos.get(type)){

         ((TextView)currChild.findViewById(R.id.durItemContent)).setTextColor(Color.BLACK);
                currChild.setBackgroundColor(Color.CYAN);
            }
            else{

          ((TextView)currChild.findViewById(R.id.durItemContent)).setTextColor(Color.GRAY);
                currChild.setBackgroundColor(Color.WHITE);
            }
        }
    }

3. Макет для одного предмета (день или час)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:background="@color/white"
    >
    <TextView
        android:id="@+id/durItemContent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:textStyle="bold"
        android:textColor="@color/gray"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/blue"
        />
</LinearLayout>

4. Макет для всплывающего окна:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <LinearLayout
        android:id="@+id/daysWrapper"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_marginStart="30dp"
        android:orientation="vertical"
        android:layout_toStartOf="@+id/vertSepLine"
        android:background="@color/white"
        android:layout_centerVertical="true"
        android:layout_centerInParent="true"
        android:touchscreenBlocksFocus = "false"
        >
        <TextView
            android:id="@+id/daysTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Days"
            android:background="@color/white"
            android:textStyle="bold"
            android:textColor="@color/blue"
            android:textSize="22sp"
            android:layout_gravity="center_horizontal"
            />
        <TextView
            android:id="@+id/vertULine1"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/cyanBlue" />
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            >
            <LinearLayout
                android:id="@+id/daysOpsList"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:background="@color/white"
                >
        </LinearLayout>
        </ScrollView>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/hoursWrapper"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_marginEnd="30dp"
        android:layout_toEndOf="@+id/vertSepLine"
        android:orientation="vertical"
        android:background="@color/white"
        android:layout_alignTop="@id/daysWrapper"
        android:touchscreenBlocksFocus = "false"
        >
        <TextView
            android:id="@+id/hoursTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hours"
            android:background="@color/white"
            android:layout_gravity="center_horizontal"
            android:textStyle="bold"
            android:textColor="@color/blue"
            android:textSize="22sp"
            />
        <TextView
            android:id="@+id/vertULine2"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/cyanBlue" />
        <ScrollView
            android:layout_width="match_parent"
            android:background="@color/white"
            android:layout_height="wrap_content"
            >
            <LinearLayout
                android:id="@+id/hoursOpsList"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:background="@color/white"
                >
            </LinearLayout>
        </ScrollView>
    </LinearLayout>

    <TextView
        android:id="@+id/leftVertSep"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:layout_alignTop="@id/daysWrapper"
        android:layout_above="@id/finishButton"
        android:layout_alignStart="@id/horizSepLine"
        android:background="@color/cyanBlue" />
    <TextView
        android:id="@+id/rightVertSep"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:layout_alignTop= "@+id/horizSepLine"
        android:layout_above="@id/finishButton"
        android:layout_alignEnd="@id/horizSepLine"
        android:background="@color/cyanBlue" />
    <TextView
        android:id="@+id/vertSepLine"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:layout_alignTop= "@+id/horizSepLine"
        android:layout_centerHorizontal="true"
        android:layout_above="@id/finishButton"
        android:background="@color/cyanBlue" />
    <TextView
        android:id="@+id/horizSepLine"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:layout_above="@+id/daysWrapper"
        android:layout_marginStart="30dp"
        android:layout_marginEnd="30dp"
        android:background="@color/cyanBlue" />
    <Button
        android:id="@+id/finishButton"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginStart="30dp"
        android:layout_marginEnd="30dp"
        android:text="Finish"
        android:gravity="center"
        android:textStyle="bold"
        android:textColor="@color/white"
        android:background="@color/blue"
        android:layout_below="@+id/hoursWrapper"
        />
</RelativeLayout>

5. Схема упаковки (упрощенная):

<ScrollView 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"
    tools:context=".PostCreationNew.QuestionChallengeCreation"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


         <RelativeLayout
            android:id="@+id/durationWrapper"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginStart="30dp"
            android:layout_marginEnd="30dp"
            android:layout_below="@+id/question_deadline">

            <TextView
                android:id="@+id/durationTitleV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Duration*"
                android:layout_marginStart="10dp"
                android:textColor="@color/black"
                android:layout_marginBottom="10dp"
                android:textStyle="bold"
                />
            <ImageView
                android:id="@+id/durationHintBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/ic_error_outline_grey_24dp"
                android:layout_toEndOf="@+id/durationTitleV"
                android:layout_alignTop="@+id/durationTitleV"
                android:onClick="showDurationHint"
                />

            <RelativeLayout
                android:id="@+id/durationBody"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:layout_below="@+id/durationTitleV"
                android:onClick="showDurationPopup"
                >
                <RelativeLayout
                    android:id="@+id/wrapper"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    >
                    <TextView
                        android:id="@+id/currDurInfoView"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/blue"
                        android:layout_marginStart="10dp"
                        android:textStyle="bold"
                        android:textSize="22sp"
                        android:visibility="gone"
                        android:onClick="showDurationPopup"
                        android:drawableEnd="@drawable/ic_arrow"
                        />
                    <TextView
                        android:id="@+id/question_duration_edit"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="click here"
                        android:paddingLeft="10dp"
                        android:layout_marginBottom="10dp"
                        android:layout_below="@id/currDurInfoView"
                        />
                </RelativeLayout>
                <TextView
                    android:id="@+id/underline"
                    android:layout_width="wrap_content"
                    android:layout_height="1dp"
                    android:layout_alignBottom="@+id/wrapper"
                    android:layout_alignStart="@+id/wrapper"
                    android:layout_alignEnd="@+id/wrapper"
                    android:background="@color/blue"
                    />
            </RelativeLayout>
        </RelativeLayout>
</ScrollView>
...