Специальное уведомление Android, не отображающее изменения кода

Там какое-то странное поведение. У меня есть куча кода, картинки, а затем некоторое описание странного поведения и затем мои вопросы.

Файлы

У меня есть файл random_start_bonus_cards_notification.xml, который выглядит так:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:gravity="center">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/firstCard" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/secondCard" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ifNotCoal"
        android:visibility="gone">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="("
            android:paddingTop="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/if_not_coal"
            android:paddingTop="15dp" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/thirdCard" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=")"
            android:paddingTop="15dp" />

    </LinearLayout>

И файл random_start_bonus_cards.xml

<?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"></RelativeLayout>

Это преднамеренно пустой макет, из-за странности мы займемся. Оказывается, этот файл должен быть здесь, но не имеет значения, что он содержит.

Annnnd my styles.xml:

<resources>
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
</style>

<style name="NotificationTitle">
    <item name="android:textColor">?android:attr/textColorPrimaryInverse</item>
    <item name="android:textStyle">bold</item>
</style>
<style name="NotificationText">
    <item name="android:textColor">?android:attr/textColorPrimaryInverse</item>
</style>

И некоторые Android-коды:

    private void showStartBonusCardsDialog(DrawnCards drawnCards) {
    LayoutInflater factory = LayoutInflater.from(CalculatorActivity.this);
    final View dialogContent = factory.inflate(R.layout.random_start_bonus_cards_notification, null);
    ((ImageView) dialogContent.findViewById(R.id.firstCard)).setImageResource(getDrawableIdForStartCard(drawnCards.firstCard()));
    ((ImageView) dialogContent.findViewById(R.id.secondCard)).setImageResource(getDrawableIdForStartCard(drawnCards.secondCard()));

    if(drawnCards.hasThirdCard()) {
        dialogContent.findViewById(R.id.ifNotCoal).setVisibility(View.VISIBLE);
        ((ImageView) dialogContent.findViewById(R.id.thirdCard)).setImageResource(getDrawableIdForStartCard(drawnCards.thirdCard()));
    } else {
        dialogContent.findViewById(R.id.ifNotCoal).setVisibility(View.GONE);
    }

    AlertDialog drawnCardsDialog = new AlertDialog.Builder(CalculatorActivity.this).create();
    drawnCardsDialog.setView(dialogContent);
    drawnCardsDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); }
    });
    drawnCardsDialog.show();
}

private void showStartBonusCardsNotification(DrawnCards drawnCards) {
    Intent openIntent = new Intent(CalculatorActivity.this, CalculatorActivity.class);
    openIntent.setAction(refreshStartCardsAction);
    PendingIntent openPendingIntent = PendingIntent.getActivity(this, 0, openIntent, 0);

    RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.random_start_bonus_cards_notification);
    notificationView.setImageViewResource(R.id.firstCard, getDrawableIdForStartCard(drawnCards.firstCard()));
    notificationView.setImageViewResource(R.id.secondCard, getDrawableIdForStartCard(drawnCards.secondCard()));
    if(drawnCards.hasThirdCard()) {
        notificationView.setViewVisibility(R.id.ifNotCoal, View.VISIBLE);
        notificationView.setImageViewResource(R.id.thirdCard, getDrawableIdForStartCard(drawnCards.thirdCard()));
    } else {
        notificationView.setViewVisibility(R.id.ifNotCoal, View.GONE);
    }

    NotificationCompat.Builder notification = new NotificationCompat.Builder(this);
    notification.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    notification.setSmallIcon(R.drawable.white);
    notification.setContentIntent(openPendingIntent);
    notification.setContent(notificationView);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    int notificationId = 1;
    notificationManager.notify(notificationId, notification.build());
}

И вот два скриншота, на которые нужно ссылаться: Диалог Уведомление

Weirdness

Сначала у меня был только один файл макета, так как макеты были одинаковыми. При этом цвет текста диалога был черным (хорошо), а цвет текста уведомления был белым и не мог быть прочитан на моем HTC M9.

(1) Если я поместил XML из random_start_bonus_cards_notification.xml в random_start_bonus_cards.xml и заменил все использования random_start_bonus_cards_notification на random_start_bonus_cards, цвета текста ошибочны. Если я сохраню код как есть, но удалю random_start_bonus_cards, цвета текста неправильные. Если я использую random_start_bonus_cards_notification.xml и сохраняю random_start_bonus_cards.xml в проекте, даже если он пуст, я получаю черный текст как в диалоговом окне, так и в уведомлении!

(2) Фон уведомления является бледно-зеленым. Этот цвет был в файле ресурсов в одной точке, но был удален (как показано). После удаления цвета фона макет диалога имеет белый фон, но фон уведомлений по-прежнему бледно-зеленый, независимо от того, изменяю ли он его на красный или что-то еще.

(3) Если я перестаю вызывать код диалога, произойдет такое же поведение. Я включил код диалога, так как я беспокоюсь, что здесь может быть какое-то взаимодействие, но я не понимаю, как это сделать.

Вопросы

Как правило, как работает RemoteViews с настраиваемыми макетами уведомлений? Существует ли какое-либо системное кэширование, которое могло бы учитывать цвет фона, который не меняется?

Почему мое уведомление не меняет цвет фона при изменении цвета фона макета?

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

Почему мой цвет текста уведомлений не работает, если я не использую файл с именем random_start_bonus_cards_notification.xml? (Если я удалю _notification, текст меняет цвет).

Спасибо за чтение!

Ответы

Ответ 1

Это было безумие, и оно все еще не велико.

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

(2) Я оставил уведомление с отдельными файлами макета из диалога, хотя они идентичны. Мое рассуждение состоит в том, что, по-видимому, фон уведомлений может меняться между релизами Android (там много жалоб).

(3) Я не размещал его выше, но в какой-то момент у меня был "v9/styles.xml". Я не понял, что это применимо ко всем версиям выше API9.

Окончательное решение похоже на следующий код. Я скопировал из этого SO ответ (5.1.1 уведомление TextView, правильный способ справиться с белым текстом?) и использовал textAppearance вместо стиля.

        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/if_not_coal"
        android:textAppearance="@style/NotificationText"
        android:paddingTop="15dp" />

textAppearance отлично.

<style name="NotificationText" parent="android:TextAppearance.StatusBar.EventContent" />

Дает текст серому цвету для < API 21.

<style name="NotificationText" parent="@android:style/TextAppearance.Material.Notification.Title"></style>

Дает текст черному цвету для API >= 21.

Ответ 2

Я предполагаю, что это происходит по одной из следующих двух причин:

  • Первым из них может быть то, что где-то еще в вашем коде, вы ссылаетесь на создание уведомления, и там сделанные вами изменения не повлияют на код.

  • Это, скорее всего, произойдет. Сборка сломана, и ваша встроенная версия приложения не использует последний код. Вы можете решить это, перестроив приложение из вашей среды IDE.

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

Надеюсь, что это поможет:)