---
title: "Afficher un graphique interactif d'objectif de poids dans un paywall"
description: "Affichez le poids projeté de chaque utilisateur sous forme de graphique dans un flow de paywall. Les utilisateurs font glisser leur doigt sur le graphique pour voir leur poids pour n'importe quelle semaine."
---

> **AI agents**: to search Adapty docs faster and with fewer tokens, install the Adapty skills: `npx adapty skills install --yes`

Suivez cette recette pour afficher le poids projeté de chaque utilisateur sous forme de graphique dans un flow de paywall. L'utilisateur saisit son poids actuel et son poids cible dans un flow d'onboarding. Votre application collecte ces deux valeurs. Le graphique affiche la progression hebdomadaire que l'utilisateur peut espérer avec votre application, de l'une à l'autre. Votre application affiche le graphique sous forme de vue native dans un [élément personnalisé](flow-custom-elements). La vue dessine le graphique sans bibliothèque de graphiques.

## Avant de commencer \{#before-you-start\}

<Tabs groupId="current-os" queryString>
<TabItem value="kotlin" label="Kotlin" default>

- Mettez à jour votre application vers Adapty Android SDK 4.4 ou une version ultérieure. Les versions antérieures du SDK affichent le [contenu de secours](flow-custom-elements#set-fallback-content) pour chaque élément personnalisé.
- Configurez votre application pour [récupérer](android-get-pb-paywalls) et [afficher](android-present-paywalls) les flows.
- Configurez Jetpack Compose dans votre module d'application. Le graphique dans cette recette est un composable.
- Ajoutez Compose Foundation à votre application via Gradle, depuis `androidx.compose.foundation:foundation`.

</TabItem>
<TabItem value="java" label="Java">

- Mettez à jour votre application vers Adapty Android SDK 4.4 ou version ultérieure. Les versions antérieures du SDK affichent le [contenu de secours](flow-custom-elements#set-fallback-content) pour chaque élément personnalisé.
- Configurez votre application pour [récupérer](android-get-pb-paywalls) et [afficher](android-present-paywalls) les flows.

</TabItem>
</Tabs>

Créez deux flows distincts — un pour l'onboarding, et un pour le paywall. Ajoutez chacun à un [placement](placements). Le code de cette recette récupère le flow du paywall depuis le placement avec l'ID `weight_paywall`.

## 1. Demander le poids actuel et l'objectif dans le flow d'onboarding \{#1-ask-for-the-current-and-goal-weight-in-the-onboarding-flow\}

Dans le Flow & Paywall Builder, ajoutez deux saisies [**Number**](builder-inputs-and-forms) à l'onboarding flow :

- Une pour le poids actuel en kilogrammes, avec l'**Element ID** `weight`.
- Une pour le poids cible en kilogrammes, avec l'**Element ID** `goal_weight`.

Pour que votre application lise les poids de la même façon dans toutes les langues, sélectionnez **Integer** dans le menu déroulant **Format** des deux saisies. Une saisie envoie sa valeur à votre application sous forme de texte, exactement tel que l'utilisateur l'a tapé. Le code de cette recette interprète « 70.5 » et « 70,5 » différemment. Les nombres entiers n'ont pas de séparateur décimal.

Pour vous assurer que votre application reçoive les deux valeurs, terminez l'onboarding flow par un écran sans saisies. Sur cet écran, ajoutez un bouton avec l'action [**Close flow**](onboarding-actions#close-flow). Les saisies envoient leurs valeurs lorsqu'elles perdent le focus ou lorsque l'utilisateur passe à un autre écran.

## 2. Ajouter l'élément personnalisé à l'écran du paywall \{#2-add-the-custom-element-to-the-paywall-screen\}

Dans le flow du paywall, [ajoutez un élément personnalisé](flow-custom-elements#add-and-configure) à un écran et configurez-le pour le graphique :

- **Type** : `line_chart`.
- **ID** : `weight_goal`.
- **Hauteur** : Conservez la hauteur **Fixed** par défaut. Le graphique remplit l'élément personnalisé.

Ne placez pas l'élément personnalisé dans des conteneurs qui répondent au toucher, comme un carousel, afin que seul le graphique réagisse au glissement.

À l'intérieur de l'élément personnalisé, ajoutez une [**Image**](custom-media#image) avec un exemple de graphique de poids. Les utilisateurs la voient comme [contenu de secours](flow-custom-elements#set-fallback-content) lorsque leur version de votre application n'affiche pas le graphique.

## 3. Enregistrer le poids actuel et l'objectif dans votre app \{#3-save-the-current-and-goal-weight-in-your-app\}

Récupérez le poids actuel et l'objectif à partir des événements `flow_user_input` du flow d'onboarding, comme indiqué dans [Traiter les données des flows](android-flow-input). Pour savoir que l'utilisateur a atteint le dernier écran, surveillez un événement `flow_screen_showed` avec `is_last_screen` défini à `true`. Lorsque le flow d'onboarding se ferme après cet écran, transmettez les deux poids à `showWeightPaywall`, la fonction qui [ouvre le flow de paywall avec le graphique](#5-match-the-chart-to-the-custom-element).

<Tabs groupId="current-os" queryString>
<TabItem value="kotlin" label="Kotlin" default>

```kotlin showLineNumbers title="Kotlin"

class WeightOnboardingListener(
    private val activity: Activity, // the activity that displays the paywall flow
) : AdaptyFlowDefaultEventListener() {

    private val enteredWeights = mutableMapOf<String, String>()
    private var reachedLastScreen = false

    override fun onAnalyticEvent(
        name: String,
        params: Map<String, Any?>,
        context: Context,
    ) {
        if (name == "flow_screen_showed" && params["is_last_screen"] == true) {
            reachedLastScreen = true
            return
        }
        if (name != "flow_user_input") return

        val elementId = params["element_id"] as? String ?: return
        val value = params["value"] as? String ?: return

        enteredWeights[elementId] = value
    }

    override fun onActionPerformed(action: AdaptyUI.Action, context: Context) {
        // number inputs send their values as strings
        val currentWeight = enteredWeights["weight"]?.toDoubleOrNull()
        val goalWeight = enteredWeights["goal_weight"]?.toDoubleOrNull()

        if (action == AdaptyUI.Action.Close && reachedLastScreen &&
            currentWeight != null && goalWeight != null
        ) {
            // on the last screen, open the paywall flow in place of the onboarding flow
            showWeightPaywall(activity, currentWeight, goalWeight)
        } else {
            super.onActionPerformed(action, context) // the default handling, such as going back
        }
    }
}
```

Pour le flow d'onboarding, passez `WeightOnboardingListener` dans le paramètre `eventListener` de `AdaptyUI.getFlowView`. Créez le listener avec l'activité qui affiche le flow de paywall.

Dans Jetpack Compose, passez le listener à `AdaptyFlowScreen` à la place, et affichez le flow de paywall dans un second `AdaptyFlowScreen`.

</TabItem>
<TabItem value="java" label="Java">

```java showLineNumbers title="Java"

public class WeightOnboardingListener extends AdaptyFlowDefaultEventListener {
    private final Activity activity; // the activity that displays the paywall flow
    private final Map<String, String> enteredWeights = new HashMap<>();
    private boolean reachedLastScreen = false;

    public WeightOnboardingListener(Activity activity) {
        this.activity = activity;
    }

    @Override
    public void onAnalyticEvent(String name, Map<String, ?> params, Context context) {
        if (name.equals("flow_screen_showed") && Boolean.TRUE.equals(params.get("is_last_screen"))) {
            reachedLastScreen = true;
            return;
        }
        if (!name.equals("flow_user_input")) return;

        Object elementId = params.get("element_id");
        Object value = params.get("value");
        if (elementId instanceof String && value instanceof String) {
            enteredWeights.put((String) elementId, (String) value);
        }
    }

    @Override
    public void onActionPerformed(AdaptyUI.Action action, Context context) {
        // number inputs send their values as strings
        Double currentWeight = parseWeight(enteredWeights.get("weight"));
        Double goalWeight = parseWeight(enteredWeights.get("goal_weight"));

        if (action instanceof AdaptyUI.Action.Close && reachedLastScreen
                && currentWeight != null && goalWeight != null) {
            // on the last screen, open the paywall flow in place of the onboarding flow
            WeightPaywall.showWeightPaywall(activity, currentWeight, goalWeight);
        } else {
            super.onActionPerformed(action, context); // the default handling, such as going back
        }
    }

    private static Double parseWeight(String value) {
        if (value == null) return null;
        try {
            return Double.parseDouble(value);
        } catch (NumberFormatException e) {
            return null;
        }
    }
}
```

Pour le flow d'onboarding, passez `WeightOnboardingListener` dans le paramètre `eventListener` de `AdaptyUI.getFlowView`. Créez le listener avec l'activité qui affiche le flow de paywall.

</TabItem>
</Tabs>

Lorsque l'utilisateur appuie sur le bouton avec l'action [**Close flow**](android-handle-paywall-actions#close-flows-and-paywalls) sur le dernier écran, le listener ouvre le flow de paywall à la place du flow d'onboarding.

## 4. Créer la vue du graphique \{#create-the-chart-view\}

Créez un modèle de plan de poids et une vue avec le graphique. Le plan comporte une entrée par semaine, du poids actuel jusqu'au poids cible. Lorsque l'utilisateur fait glisser son doigt sur le graphique, la vue marque la semaine au point de contact et affiche le poids prévu pour cette semaine :

<Tabs groupId="current-os" queryString>
<TabItem value="kotlin" label="Kotlin" default>

```kotlin showLineNumbers title="Kotlin"

class WeightPlan(currentWeight: Double, goalWeight: Double) {
    // one entry per week, from the current weight to the goal weight
    val entries: List<WeightEntry> = run {
        val weeklyChange = 0.5 // kg per week
        val start = System.currentTimeMillis()
        val weekMillis = 7L * 24 * 60 * 60 * 1000
        val weeks = ceil(abs(goalWeight - currentWeight) / weeklyChange).toInt()
        val step = if (goalWeight < currentWeight) -weeklyChange else weeklyChange
        (0..weeks).map { week ->
            val kilograms = if (week == weeks) goalWeight else currentWeight + step * week
            WeightEntry(Date(start + week * weekMillis), kilograms)
        }
    }
}

data class WeightEntry(val date: Date, val kilograms: Double)

@Composable
fun WeightGoalChart(entries: List<WeightEntry>) {
    // the week under the finger, or null when the user isn't dragging
    var selectedIndex by remember { mutableStateOf<Int?>(null) }
    val textMeasurer = rememberTextMeasurer()
    val dateFormat = remember { DateFormat.getDateInstance(DateFormat.MEDIUM) }
    val color = Color(0xFFAF52DE)
    val textStyle = TextStyle(color = Color.Gray, fontSize = 12.sp)
    val minKg = entries.minOf { it.kilograms }
    val kgRange = (entries.maxOf { it.kilograms } - minKg).coerceAtLeast(1.0)

    Canvas(
        Modifier
            .fillMaxSize()
            .pointerInput(entries) {
                // horizontal drags select a week; vertical drags scroll the screen
                detectHorizontalDragGestures(
                    onDragEnd = { selectedIndex = null },
                    onDragCancel = { selectedIndex = null },
                ) { change, _ ->
                    val index = (change.position.x / size.width * entries.lastIndex).roundToInt()
                    selectedIndex = index.coerceIn(0, entries.lastIndex)
                }
            }
    ) {
        val startDate = textMeasurer.measure(dateFormat.format(entries.first().date), textStyle)
        val endDate = textMeasurer.measure(dateFormat.format(entries.last().date), textStyle)
        val dateY = size.height - startDate.size.height
        val top = 24.dp.toPx() // room for the projected weight above the line
        val bottom = dateY - 8.dp.toPx()
        fun pointOf(index: Int) = Offset(
            x = size.width * index / entries.lastIndex.coerceAtLeast(1),
            y = bottom - ((entries[index].kilograms - minKg) / kgRange * (bottom - top)).toFloat(),
        )

        // the line from the current weight to the goal weight
        for (index in 1..entries.lastIndex) {
            drawLine(color, pointOf(index - 1), pointOf(index), strokeWidth = 2.dp.toPx())
        }
        // the dates of the first and the last week
        drawText(startDate, topLeft = Offset(0f, dateY))
        drawText(endDate, topLeft = Offset(size.width - endDate.size.width, dateY))

        // the selected week: a point, and the projected weight above it
        selectedIndex?.let { index ->
            val point = pointOf(index)
            drawCircle(color, radius = 5.dp.toPx(), center = point)
            val weight = String.format(Locale.getDefault(), "%.1f kg", entries[index].kilograms)
            val label = textMeasurer.measure(weight, textStyle.copy(color = color))
            val x = (point.x - label.size.width / 2)
                .coerceAtMost(size.width - label.size.width)
                .coerceAtLeast(0f)
            drawText(label, topLeft = Offset(x, point.y - label.size.height - 8.dp.toPx()))
        }
    }
}
```

</TabItem>
<TabItem value="java" label="Java">

```java showLineNumbers title="Java"

public class WeightPlan {
    // one entry per week, from the current weight to the goal weight
    public final List<WeightEntry> entries = new ArrayList<>();

    public WeightPlan(double currentWeight, double goalWeight) {
        double weeklyChange = 0.5; // kg per week
        long start = System.currentTimeMillis();
        long weekMillis = 7L * 24 * 60 * 60 * 1000;
        int weeks = (int) Math.ceil(Math.abs(goalWeight - currentWeight) / weeklyChange);
        double step = goalWeight < currentWeight ? -weeklyChange : weeklyChange;
        for (int week = 0; week <= weeks; week++) {
            double kilograms = week == weeks ? goalWeight : currentWeight + step * week;
            entries.add(new WeightEntry(new Date(start + week * weekMillis), kilograms));
        }
    }
}

public class WeightEntry {
    public final Date date;
    public final double kilograms;

    public WeightEntry(Date date, double kilograms) {
        this.date = date;
        this.kilograms = kilograms;
    }
}

public class WeightGoalChartView extends View {
    private final List<WeightEntry> entries;
    private final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
    private final Paint chartPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private final Paint datePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private final float density = getResources().getDisplayMetrics().density;
    private final int touchSlop;
    private double minKg = Double.MAX_VALUE;
    private double maxKg = -Double.MAX_VALUE;
    private float downX;
    private float downY;
    // the week under the finger, or -1 when the user isn't dragging
    private int selectedIndex = -1;

    public WeightGoalChartView(Context context, List<WeightEntry> entries) {
        super(context);
        this.entries = entries;
        touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        float textSize = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics());
        chartPaint.setColor(0xFFAF52DE);
        chartPaint.setStrokeWidth(2 * density);
        chartPaint.setTextSize(textSize);
        datePaint.setColor(Color.GRAY);
        datePaint.setTextSize(textSize);
        for (WeightEntry entry : entries) {
            minKg = Math.min(minKg, entry.kilograms);
            maxKg = Math.max(maxKg, entry.kilograms);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // the line from the current weight to the goal weight
        for (int index = 1; index < entries.size(); index++) {
            canvas.drawLine(xOf(index - 1), yOf(index - 1), xOf(index), yOf(index), chartPaint);
        }
        // the dates of the first and the last week
        String endDate = dateFormat.format(entries.get(entries.size() - 1).date);
        float dateY = getHeight() - datePaint.descent();
        canvas.drawText(dateFormat.format(entries.get(0).date), 0, dateY, datePaint);
        canvas.drawText(endDate, getWidth() - datePaint.measureText(endDate), dateY, datePaint);

        // the selected week: a point, and the projected weight above it
        if (selectedIndex >= 0) {
            float x = xOf(selectedIndex);
            float y = yOf(selectedIndex);
            canvas.drawCircle(x, y, 5 * density, chartPaint);
            double kilograms = entries.get(selectedIndex).kilograms;
            String weight = String.format(Locale.getDefault(), "%.1f kg", kilograms);
            float width = chartPaint.measureText(weight);
            float labelX = Math.max(0, Math.min(x - width / 2, getWidth() - width));
            canvas.drawText(weight, labelX, y - 8 * density, chartPaint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();
                downY = event.getY();
                return true;
            case MotionEvent.ACTION_MOVE:
                // horizontal drags select a week; vertical drags scroll the screen
                float dx = Math.abs(event.getX() - downX);
                if (selectedIndex < 0 && (dx < touchSlop || dx < Math.abs(event.getY() - downY))) {
                    return true;
                }
                getParent().requestDisallowInterceptTouchEvent(true);
                int index = Math.round(event.getX() / getWidth() * (entries.size() - 1));
                selectedIndex = Math.max(0, Math.min(index, entries.size() - 1));
                invalidate();
                return true;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                selectedIndex = -1;
                invalidate();
                return true;
        }
        return super.onTouchEvent(event);
    }

    private float xOf(int index) {
        return getWidth() * index / (float) Math.max(entries.size() - 1, 1);
    }

    private float yOf(int index) {
        float top = 24 * density; // room for the projected weight above the line
        float bottom = getHeight() - datePaint.getFontSpacing() - 8 * density; // room for the dates
        double fraction = (entries.get(index).kilograms - minKg) / Math.max(maxKg - minKg, 1);
        return (float) (bottom - fraction * (bottom - top));
    }
}
```

</TabItem>
</Tabs>

Le plan suppose que le poids évolue de 0,5 kg par semaine. Pour utiliser un autre taux, modifiez `weeklyChange`.

## 5. Associer le graphique à l'élément personnalisé \{#5-match-the-chart-to-the-custom-element\}

Écrivez un [resolver](android-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views) qui retourne la vue du graphique pour le Type `line_chart` et l'ID `weight_goal`. Stockez le plan de poids dans une propriété du resolver :

<Tabs groupId="current-os" queryString>
<TabItem value="kotlin" label="Kotlin" default>

```kotlin showLineNumbers title="Kotlin"

class WeightChartResolver(
    private val plan: WeightPlan,
) : AdaptyCustomElementsResolver {

    override fun resolve(type: String, id: String): AdaptyCustomElementContent? =
        if (type == "line_chart" && id == "weight_goal") {
            AdaptyCustomElementContent.compose { WeightGoalChart(plan.entries) }
        } else {
            null // another custom element: show the fallback
        }
}
```

</TabItem>
<TabItem value="java" label="Java">

```java showLineNumbers title="Java"

public class WeightChartResolver implements AdaptyCustomElementsResolver {
    private final WeightPlan plan;

    public WeightChartResolver(WeightPlan plan) {
        this.plan = plan;
    }

    @Override
    public AdaptyCustomElementContent resolve(String type, String id) {
        if (type.equals("line_chart") && id.equals("weight_goal")) {
            return AdaptyCustomElementContent.view(
                    (context, elementContext) -> new WeightGoalChartView(context, plan.entries)
            );
        }
        return null; // another custom element: show the fallback
    }
}
```

</TabItem>
</Tabs>

Attachez le resolver lors de la création de la vue du flow de paywall. Créez le resolver avec le plan de poids à partir du poids actuel et du poids cible :

<Tabs groupId="current-os" queryString>
<TabItem value="kotlin" label="Kotlin" default>

```kotlin showLineNumbers title="Kotlin"

fun showWeightPaywall(activity: Activity, currentWeight: Double, goalWeight: Double) {
    val plan = WeightPlan(currentWeight, goalWeight)
    Adapty.getFlow("weight_paywall") { flowResult ->
        if (flowResult !is AdaptyResult.Success) return@getFlow // handle the error
        AdaptyUI.getFlowConfiguration(flowResult.value) { configResult ->
            if (configResult !is AdaptyResult.Success) return@getFlowConfiguration // handle the error
            val flowView = AdaptyUI.getFlowView(
                activity,
                configResult.value,
                products = null,
                eventListener = AdaptyFlowDefaultEventListener(),
                customElementsResolver = WeightChartResolver(plan),
            )
            activity.setContentView(flowView) // in place of the onboarding flow
        }
    }
}
```

</TabItem>
<TabItem value="java" label="Java">

```java showLineNumbers title="Java"

public class WeightPaywall {
    public static void showWeightPaywall(Activity activity, double currentWeight, double goalWeight) {
        WeightPlan plan = new WeightPlan(currentWeight, goalWeight);
        Adapty.getFlow("weight_paywall", flowResult -> {
            if (!(flowResult instanceof AdaptyResult.Success)) return; // handle the error
            AdaptyFlow flow = ((AdaptyResult.Success<AdaptyFlow>) flowResult).getValue();
            AdaptyUI.getFlowConfiguration(flow, configResult -> {
                if (!(configResult instanceof AdaptyResult.Success)) return; // handle the error
                AdaptyFlowView flowView = AdaptyUI.getFlowView(
                        activity,
                        ((AdaptyResult.Success<AdaptyUI.FlowConfiguration>) configResult).getValue(),
                        null, // products
                        new AdaptyFlowDefaultEventListener(),
                        // defaults: if your app passes other values here, keep them
                        AdaptyFlowInsets.Unspecified,
                        AdaptyCustomAssets.Empty,
                        AdaptyUiTagResolver.Default,
                        AdaptyUiTimerResolver.Default,
                        null, // observerModeHandler
                        new WeightChartResolver(plan)
                );
                activity.setContentView(flowView); // in place of the onboarding flow
            });
        });
    }
}
```

</TabItem>
</Tabs>

Si votre application définit un [résolveur global](android-flow-custom-elements#display-views-in-every-flow), ce résolveur le remplace dans le flow du paywall. `WeightChartResolver` ne renvoie aucune vue pour les autres Types et IDs, car le flow du paywall dans cette recette ne contient pas d'autres éléments personnalisés. Si votre flow de paywall possède d'autres éléments personnalisés, transmettez le résolveur global à celui-ci. Appelez ensuite le résolveur global pour leurs Types et IDs, comme dans [Afficher les données pour un seul flow](android-flow-custom-elements#display-data-for-one-flow).

## 6. Tester sur un appareil \{#6-test-on-a-device\}

Le Flow & Paywall Builder ne peut pas exécuter le code de votre application, donc son canvas affiche uniquement le paywall de secours. Pour prévisualiser le graphique :

1. [Publiez les deux flows](builder-save-publish). Pour voir les dernières versions publiées plutôt que les versions mises en cache, enregistrez l'appareil en tant que [device de test](test-devices).
2. Lancez un build de votre application qui inclut le resolver. Complétez le flow d'onboarding avec un poids actuel et un poids cible. Vérifiez que la ligne du graphique commence au poids actuel et se termine au poids cible.
3. Faites glisser votre doigt sur le graphique et vérifiez que le poids prévu pour la semaine sous votre doigt s'affiche au-dessus de la ligne.

Pour tester le fallback, faites en sorte que `WeightChartResolver` renvoie `null`, puis ouvrez à nouveau le flow du paywall.

Pour savoir pourquoi le paywall de secours s'affiche à la place du graphique, suivez les instructions de la section [Tester sur un appareil](android-flow-custom-elements#test-on-a-device) du guide Android.