Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] kotlin – Android app widget’s visibility is not updated

Posted on November 11, 2022 By

Solution 1 :

Like Mike.M says in the comments, you’re not setting the visibility on your prev button, because it has a different ID to the view you’re changing in code:

<ImageButton android_id="@+id/buttonPrev"
else views.setViewVisibility(R.id.buttonBack, View.GONE)

So that’s why nothing’s happening to that button.


Your next button disappears forever because you’re not actually making it visible again. You hide it when index >= 10, but there’s no code that shows it when index < 10

You need to think of the button as having states, let’s call them ACTIVE and INACTIVE. Each state describes stuff about a button (in your case, whether it’s visible or not), and your condition check works out which state a button should be in.

Then you need to apply that state to the button, so it always reflects the current state:

if (index < 10) {
    views.setOnClickPendingIntent(
        R.id.buttonNext,
        pendingIntent(context, "next")
    )
    // it's in the ACTIVE state, so it MUST BE VISIBLE
    views.setViewVisibility(R.id.buttonNext, View.VISIBLE)
} else {
    // it's in the ACTIVE state, so it MUST NOT BE VISIBLE
    views.setViewVisibility(R.id.buttonNext, View.GONE)
}

Doing things this way means when you call the update function, it always displays as it should. You don’t need to know anything about its previous state, if it’s currently visible, if it’s been set up, or anything like that. You just declare how it should be, in every case. It makes it way easier to read and reason about, and you avoid bugs like stuff showing parts of their old state (if you get into RecyclerViews, setting the state of the whole item display is real important since the displays get reused)

READ  [FIXED] java - Error 400, Bad Request, Json Parse error: Unrecognized token 'agama' : was Expecting ('true','false', or 'null') in Android Retrofit with Spring Boot
Powered by Inline Related Posts

You’ll need to do the same for the other button of course 😉

Problem :

I reduced a bigger portion of code to this easy to test AppWidgetProvider class and I still have this problem.

Basically, I have a simple navigation part with a prev and next button. If the index is 0 , the prev button should be gone, if index is 10, the next button is gone. When it’s in between, both buttons are displayed. Pressing the buttons increases or decreases the index, which is saved in SharedPreferences

The problem I have is that, for example, when the widget is updated for the first time (and the index is 0), the prev button is not gone. As I click the next button, I can see the index being increased and the TextView in the center shows it. When the index is 10, at least the first time I tested it, the next button is gone, but then when I go back by pressing prev and the index is lower than 10, it doesn’t show up again. And then, when I get to index 0, the prev button is not gone.

So, it’s all this sort of weird behaviour that has to do with updating the widget that I have been going nuts with.

class DemoWidget : AppWidgetProvider() {
    override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
        super.onUpdate(context, appWidgetManager, appWidgetIds)
        for (appWidgetId in appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId)
        }
    }

    override fun onReceive(context: Context, intent: Intent) {
        super.onReceive(context, intent)

        val action = intent.action ?: ""

        if (action == "prev") {
            setIndex(context, getIndex(context) - 1)

            updateAppWidgets(context)
        } else if (action == "next") {
            setIndex(context, getIndex(context) + 1)

            updateAppWidgets(context)
        }
    }

    private fun updateAppWidgets(context: Context) {
        val manager = AppWidgetManager.getInstance(context)
        val ids = manager.getAppWidgetIds(ComponentName(context, javaClass))
        ids.forEach {
            updateAppWidget(context, manager, it)
        }
    }

    private fun getIndex(context: Context): Int {
        val prefs = context.getSharedPreferences(context.packageName, 0)
        return prefs.getInt("index", 0)
    }

    private fun setIndex(context: Context, prefValue: Int) {
        val prefs = context.getSharedPreferences(context.packageName, 0).edit()
        prefs.putInt("index", prefValue)
        prefs.apply()
    }

    private fun pendingIntent(context: Context?, action: String? = null): PendingIntent? {
        val intent = Intent(context, javaClass)
        intent.action = action

        return PendingIntent.getBroadcast(
            context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
    }

    private fun updateAppWidget(context: Context, manager: AppWidgetManager, widgetId: Int) {
        val views = RemoteViews(context.packageName, R.layout.demo_widget)

        val index = getIndex(context)

        views.setTextViewText(R.id.textViewIndex, index.toString())

        if (index > 0) {
            views.setOnClickPendingIntent(
                R.id.buttonPrev,
                pendingIntent(context, "prev")
            )
        } else {
            views.setViewVisibility(R.id.buttonBack, View.GONE)
        }

        if (index < 10) {
            views.setOnClickPendingIntent(
                R.id.buttonNext,
                pendingIntent(context, "next")
            )
        } else {
            views.setViewVisibility(R.id.buttonNext, View.GONE)
        }

        manager.updateAppWidget(widgetId, views)
    }
}

and my layout

<FrameLayout xmlns_android="http://schemas.android.com/apk/res/android"
    style="@style/Widget.Demo.AppWidget.Container"
    android_id="@+id/layoutWidget"
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_theme="@style/Theme.Demo.AppWidgetContainer">

    <ImageButton
        android_id="@+id/buttonPrev"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_gravity="start|center_vertical"
        android_background="@android:color/transparent"
        android_contentDescription="@string/back"
        android_src="@drawable/app_widget_back_background" />

    <TextView
        android_id="@+id/textViewIndex"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_gravity="center"
        android_padding="@dimen/widget_menu_padding"
        android_textColor="@color/white"
        android_textAlignment="center" />

    <ImageButton
        android_id="@+id/buttonNext"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_gravity="end|center_vertical"
        android_background="@android:color/transparent"
        android_contentDescription="@string/forward"
        android_src="@drawable/app_widget_forward_background" />

</FrameLayout>

The Manifest file, if you need it

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns_android="http://schemas.android.com/apk/res/android">
    <application
        android_icon="@mipmap/ic_launcher"
        android_label="@string/app_name"
        android_theme="@style/Theme.Demo">

        <receiver
            android_name=".DemoWidget"
            android_exported="true">
            <intent-filter>
                <action android_name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data
                android_name="android.appwidget.provider"
                android_resource="@xml/demo_widget_info" />
        </receiver>
    </application>
</manifest>

Provider info (v31)

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns_android="http://schemas.android.com/apk/res/android"
    android_description="@string/app_description"
    android_initialLayout="@layout/demo_widget"
    android_minWidth="@dimen/widget_min_width"
    android_minHeight="@dimen/widget_min_height"
    android_previewImage="@drawable/app_widget_preview"
    android_preAviewLayout="@layout/demo_widget"
    android_resizeMode="horizontal|vertical"
    android_targetCellWidth="1"
    android_targetCellHeight="1"
    android_updatePeriodMillis="86400000"
    android_widgetCategory="home_screen" />

Comments

Comment posted by Mike M.

views.setViewVisibility(R.id.buttonBack, View.GONE)

Android Tags:android, android-appwidget, kotlin, visibility

Post navigation

Previous Post: [FIXED] android – How to detect when third party app’s dialog box appears in React native?
Next Post: [FIXED] android – Get the list of user SIM cards and select it – flutter

Related Posts

[FIXED] typescript – checking @react-native-community/netinfo network connection in react native isconnected is not working Android
[FIXED] android – Flutter: Use different colors on text according to the situation Android
[FIXED] android – Don’t clean up RecyclerView on PagedList invalidation Android
[FIXED] Send dynamic array list to android alert set multi choice Items Android
[FIXED] java – Creating CSV files Android Android
[FIXED] android – Images are not show in the debug apk – React Native Android

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • What color are dead flea eggs?
  • What is Indiana vine?
  • What’s the downside of a Chromebook?
  • Is phosphide the same as phosphorus?
  • Why do you need an S bend?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme