0

I have a RelativeLayout with a one View object (a simple bitmap). I use getLayoutParams() and setLayoutParams() to move it, for the sake of compatibility.

But when getLayoutParams() is called from inside onSaveInstanceState() event (because screen rotated, for example), program aborts with message "The application ... has stopped unexpectedly. Please try again". Code:

@Override
    protected void onSaveInstanceState(Bundle outState) {
        View v=findViewById(R.id.MyView);
        RelativeLayout.LayoutParams lp;
        lp=(RelativeLayout.LayoutParams)v.getLayoutParams();  // **Exception!!!**

        // ... (do something with lp.leftMargin, etc)

        super.onSaveInstanceState(outState);
    }

These are the relevant exception first lines:

Caused by: java.lang.ClassCastException: android.widget.FrameLayout$LayoutParams
        at com.example.Main.onSaveInstanceState(Main.java:85)
        at android.app.Activity.performSaveInstanceState(Activity.java:1037)
        at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1181)
        at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2336)

The same happens inside onCreate() and onPause() events.

When I use getLayoutParams() inside other functions (e.g. timer event functions) it works fine.

oscar
  • 355
  • 1
  • 2
  • 13

1 Answers1

1

The method getLayoutParams returns a ViewGroup.LayoutParams. There are many, many subclasses of this, including RelativeLayout.LayoutParams. Your View v must be returning the wrong type.

If you need to use leftMargin etc you should try replacing RelativeLayout.LayoutParams with ViewGroup.MarginLayoutParams. I can't be sure it'll work as I don't know the class of v.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
  • Precise diagnostic! By mistake I was trying to obtain a `RelativeLayout.LayoutParams` class out of a `(Layout).getLayoutParams()` function, instead from an `(ImgView).getLayoutParams`. So it was a simple typecasting error... I think I didn't fully read the first line of the exception: `Caused by: java.lang.ClassCastException`. – oscar Sep 06 '15 at 12:26