java – margin doesn't work on real device

Question:

Problem: margin works in the studio emulator, but not on the tablet, what could be a trick?

I add buttons I created to the fragment, here is the button class:

import android.support.v7.widget.AppCompatButton;
import android.content.Context;
import android.graphics.Color;
import android.widget.RelativeLayout;

public class LvlButton extends AppCompatButton {

    private final int SCALE = 3;

    public LvlButton(Context context) {
        super(context);

        //margin равен 1% размера фрагмента
        int btnMargin = WindowConfiguration.getOnePercent();

        //отнимаем сумму всех марджинов и делим на кооличество кнопок в ряду
        int btnSize = (WindowConfiguration.getHeightDevice() - (WindowConfiguration.getOnePercent()*6))/SCALE;

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(btnSize,btnSize);
        layoutParams.setMargins(btnMargin,btnMargin,btnMargin,btnMargin);

        setText(String.valueOf(btnSize)+ " "+String.valueOf(WindowConfiguration.getHeightDevice()));
        setBackgroundColor(Color.BLUE);
        setLayoutParams(layoutParams);
    }
}

fragment:

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import java.util.ArrayList;


public class FragmentOfGameLevels extends Fragment {
    GridLayout table;

    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container, Bundle savedInstanceState) {
        Context context = getActivity().getBaseContext();
        table = new GridLayout(context);

        table.setColumnCount(3);
        table.setRowCount(3);

        for (int i= 0; i<9; i++){
            table.addView(new LvlButton(context));
        }
        return table;
    }

the problem is probably in the API versions

Answer:

solved the question: LayoutParams for the button must be used the same as for the container, in this case like this:

GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams(new ViewGroup.LayoutParams(btnSize,btnSize));
        layoutParams.setMargins(btnMargin,btnMargin,btnMargin,btnMargin);

instead of

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(btnSize,btnSize);
        layoutParams.setMargins(btnMargin,btnMargin,btnMargin,btnMargin);
Scroll to Top
AllEscort