setting margins on relative layout doesnt work

爷,独闯天下 提交于 2019-12-12 05:05:50

问题


I used a FragmentTransaction to add a Fragment into a FrameLayout. I want to dynamically change the margin of the RelativeLayout used by the Fragment. However, the margins are not changing with RelativeLayout.layoutParams. I also used setMargins() and it didnt work.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.infocard, container, false);

        RelativeLayout infoLayout = (RelativeLayout) view.findViewById(R.id.info);
        infoLayout.setOnClickListener(new EmptyClickListener());

        final int width = 250;
        final int height = 320;
        int leftMargin = 0;
        int topMargin = 0;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);

        if (x - width < 0) {
            leftMargin = 0;
            System.out.println("left " + leftMargin);
        }
        else {
            leftMargin = x - width;
        }

        if (y >= 450 && y <= 480) {
            topMargin = y - height;
        }

        params.leftMargin = leftMargin;
        params.topMargin = topMargin;

        infoLayout.setLayoutParams(params);

回答1:


Try using

FrameLayout.LayoutParams

instead of

RelativeLayout.LayoutParams

Layouts expect the params type to be the type from their parent container rather than the View type that you are setting them on



来源:https://stackoverflow.com/questions/9811722/setting-margins-on-relative-layout-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!