Buttons Misaligned After Loading Scaled and Dragged Positions from SharedPreferences

  Kiến thức lập trình

I’m working on an Android application where users can drag and scale buttons on the screen. The position and scale of these buttons are saved to SharedPreferences so that they can be restored when the app is reopened. However, I’m encountering an issue where buttons that have been both moved and scaled do not load back into their correct positions—they are slightly offset.

Here’s the relevant part of my ButtonManager class:

package com.example.client.Helpers;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.example.client.MainActivity;
import com.example.client.R;

import java.util.Map;

public class ButtonManager {
    private MainActivity activity; // Assuming access to MainActivity
    private ConstraintLayout layout; // Assuming buttons are added to a ConstraintLayout

    public ButtonManager(MainActivity activity, ConstraintLayout layout) {
        this.activity = activity;
        this.layout = layout;

    //////////////////// new size and position included /////////////////////////////

    public void loadButtonData() {
        Toast.makeText(activity, "Loading buttons", Toast.LENGTH_SHORT).show();
        SharedPreferences prefs = activity.getSharedPreferences("ButtonData", Context.MODE_PRIVATE);
        Map<String, ?> allData = prefs.getAll();
        for (Map.Entry<String, ?> entry : allData.entrySet()) {
            String key = entry.getKey();
            if (key.startsWith("buttonText_")) {
                int buttonId = Integer.parseInt(key.split("_")[1]);
                ConstraintLayout layout = activity.findViewById(R.id.main);
                Button existingButton = layout.findViewById(buttonId);
                if (existingButton == null) {
                    String buttonText = prefs.getString(key, "");
                    String keyCode = prefs.getString("keyCode_" + buttonId, "");

                    float translationX = prefs.getFloat("button_translationX_" + buttonId, 0f);
                    float translationY = prefs.getFloat("button_translationY_" + buttonId, 0f);
                    float scaleX = prefs.getFloat("button_scaleX_" + buttonId, 1f);
                    float scaleY = prefs.getFloat("button_scaleY_" + buttonId, 1f);

                    addButton(buttonText, keyCode, buttonId);

                    Button newButton = layout.findViewById(buttonId);
                    if (newButton != null) {
                        // Set pivot points to the top-left corner
                        // Apply the scale
                        // Apply the adjusted translation values
                        saveButtonData(buttonId, buttonText, keyCode, newButton);

    public void addButton(String text, String keycode, int buttonId) {
        // Create a ContextThemeWrapper with the app theme
        ContextThemeWrapper newButtonContext = new ContextThemeWrapper(activity, R.style.Theme_Client);

        // Create the button with the themed context
        Button newButton = new Button(newButtonContext);

        // Set the background to the drawable resource

        newButton.setId(buttonId); // Assign the provided ID

        // Now store the keycode with the ID in the map
        activity.buttonKeycodeMap.put(newButton.getId(), keycode);

        // Set onclick listener to perform action associated with the keycode
        newButton.setOnTouchListener(activity.touchListener); // Example

        // Define layout parameters for the button
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(
        params.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
        params.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
        params.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
        params.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;

        layout.addView(newButton); // Use the layout parameters when adding the view

        saveButtonData(newButton.getId(), text, keycode, newButton); // Save data

    public void saveButtonData(int buttonId, String buttonText, String keyCode, View button) {
        SharedPreferences.Editor editor = activity.getSharedPreferences("ButtonData", Context.MODE_PRIVATE).edit();
        editor.putString("buttonText_" + buttonId, buttonText);
        editor.putString("keyCode_" + buttonId, keyCode);

        // Save the button's position and size
        editor.putFloat("button_translationX_" + buttonId, button.getTranslationX());
        editor.putFloat("button_translationY_" + buttonId, button.getTranslationY());
        editor.putFloat("button_scaleX_" + buttonId, button.getScaleX());
        editor.putFloat("button_scaleY_" + buttonId, button.getScaleY());


    public void removeSavedData(int buttonId) {
        SharedPreferences.Editor editor = activity.getSharedPreferences("ButtonData", Context.MODE_PRIVATE).edit();
        editor.remove("buttonText_" + buttonId);
        editor.remove("keyCode_" + buttonId);

        // Remove the button's position and size properties
        editor.remove("button_translationX_" + buttonId);
        editor.remove("button_translationY_" + buttonId);
        editor.remove("button_scaleX_" + buttonId);
        editor.remove("button_scaleY_" + buttonId);



The buttons are initially centered in the layout when added by the user. If a button is moved but not scaled, it loads back into the correct position upon reopening the app. However, if a button is both moved and scaled, it loads into a slightly incorrect position. Strangely, if the app is closed and reopened, the buttons then load into the correct position.

I suspect the issue might be related to how the translation and scale values are being applied when the button is loaded. but idk, i’ve been stuck for a while so please if anyone could help.

I’ve tried adjusting the pivot points and ensuring the order of operations is consistent, but the problem persists. I would appreciate any insights or suggestions on how to resolve this issue.

New contributor

Star1x is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.