0

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);
heero
  • 1,941
  • 5
  • 23
  • 33

1 Answers1

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

dymmeh
  • 22,247
  • 5
  • 53
  • 60
  • For some reason, this works on a Toshiba tab running 3.2.1, however, it doesnt work on the Kindle Fire 2.3.4 – heero Mar 21 '12 at 21:27
  • Is it throwing any errors? Have you tried it the other way on the KF (the way you posted) to see if maybe its backwards? – dymmeh Mar 21 '12 at 21:31
  • It is not throwing any errors. The way I posted didnt work on the kindle fire. – heero Mar 21 '12 at 21:34
  • Strange. It may have something to do with some changes to the OS that were made for the KF.. I'm not really sure, though. The way I posted is correct and is what Android expects. If its not working then maybe try cleaning your project, uninstalling the one currently on the device, and reinstalling (just to exhaust all possibilities). If it still happens it's likely down to something specific to the way KF handles LayoutParams. – dymmeh Mar 21 '12 at 21:41
  • I made a new post specific to Kindle Fire if anyone can solve this. http://stackoverflow.com/questions/9813894/setting-margins-on-relativelayout-doesnt-work-on-kindle-fire – heero Mar 21 '12 at 23:28