Question

I am trying to create a fragment for an app that will be rotated before shown (so as to avoid changing to landscape and portrait because I wish to avoid the activity being created again).

When the first fragment is shown (a list) the user selects an option, and then the second fragment is shown as if it was in portrait. To do this I have added in the xml file of the second fragment:

android:rotation="90"

However this does not seem to work correctly, it looks like the screen was drawn in portrait mode, and then rotated by 90 degrees and then shown, this has the effect of the right and left side having a big blank, and the header of the fragment not showing correctly.

Could someone help me with this, either by helping me fix the display issue, or showing me an alternative?

Was it helpful?

Solution

I finally found the answer Change Screen Orientation programmatically using a Button

but since it is a fragment I wish to rotate not the whole screen the code is like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (mView != null) return mView; //I use this because I use the same fragment , if you use different fragments remove this
    mView = (LinearLayout) inflater.inflate(R.layout.fragment_customer_card_view, container, false);
    int w = container.getWidth();
    int h = container.getHeight();
    mView.setRotation(90);
    mView.setTranslationX((w - h) / 2);
    mView.setTranslationY((h - w) / 2);
    ViewGroup.LayoutParams lp = mView.getLayoutParams();
    lp.height = w;
    lp.width = h;
    mView.requestLayout();
    return mView;
}

hope it helps someone in the future

OTHER TIPS

Use this in the fragment where u want want orientation .

getActivity().setRequestedOrientation(
            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

If you many fragments and only one fragment u wantin portrait others should be compatible based on user then make sure to give above in fragment where u want portrait orientation always and in other fragmetns use

getActivity().setRequestedOrientation(
                ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

Does setting orientation="horizontal" not do the trick?

More generally, recreating the Activity shouldn't be a huge deal for you. You should just be able to persist all of your changes and then pull them out of the Bundle that is passed to onCreate. If that is a large problem I would reconsider some of the design choices you're making in your app.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top