Buttons Misaligned After Loading Scaled and Dragged Positions from SharedPreferences

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
                        newButton.setPivotX(0f);
                        newButton.setPivotY(0f);
                        // Apply the scale
                        newButton.setScaleX(scaleX);
                        newButton.setScaleY(scaleY);
                        // Apply the adjusted translation values
                        newButton.setTranslationX(translationX);
                        newButton.setTranslationY(translationY);
                        saveButtonData(buttonId, buttonText, keyCode, newButton);
                    }
                }
            }
        }
    }


    @SuppressLint("ClickableViewAccessibility")
    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);
        newButton.setText(text);
        newButton.setTextColor(Color.WHITE);

        // Set the background to the drawable resource
        newButton.setBackgroundResource(R.drawable.button_shape);

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


        // 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(
                ConstraintLayout.LayoutParams.WRAP_CONTENT,
                ConstraintLayout.LayoutParams.WRAP_CONTENT);
        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());

        editor.apply();
    }

    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);

        editor.apply();
    }

}

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật