saberrider
saberrider

Reputation: 585

Custom Attributes - Orientation Change

I am currently having a very specific challenge. Here is the thing:

I built a custom view, where i want to set a specific attribute from xml layout. I obtain my custom attributes in the constructor for the view. Now after a orientation change this constructor is not called again, but i set different values for my custom attributes. is there any way to automatically obtain these new values, or do i have to set them manually on orientation change (or inflate again)?

Custom View:

public MyCustomView(Context context, AttributeSet attrs) {
   super(context, attrs);
   TypedArray a = context.getTheme().obtainStyledAttributes(
        attrs,
        R.styleable.MyCustomView,
        0, 0);

   try {
       mAttr = a.getBoolean(R.styleable.MyCustomView_customAttr, false);
   } finally {
       a.recycle();
   }
}

layout-landscape

<com.me.MyCustomView
     custom:customAttr="false" />

layout-portrait

<com.me.MyCustomView
     custom:customAttr="true" />

thanks for any advice!

Upvotes: 2

Views: 473

Answers (1)

Guian
Guian

Reputation: 4688

Are you using android:configChanges="orientation" on your Activity in manifest ?

like this :

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

If you do, you are requesting for managing the orientation change by yourself, so you are responsible for recreating the view as needed (re-inflate it, yes). You can do it in the onConfigurationChanged() call in your Activity.

But if you remove this setting, the Activity should be recreated by default so, your layout would be build again with the new attributes...

As explain in this Topic : oncreate called on every re-orientation

More informations about Handling Runtime changes here.

Upvotes: 1

Related Questions