Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - add fragment with custom dimensions

Currently, I am adding a fragment using the following code.

private void addFragment(Fragment fragment, String fragmentName) {
    Log.i("Adder", "Adding fragment " + fragmentName);
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.fragment_container, fragment, fragmentName);
    fragmentTransaction.commit();
}

Following code is for resizing the added fragment.

private boolean readjustFragment(Fragment fragmentToBeAdjusted, FragmentCoordinates fragmentCoordinates) {
    if (fragmentToBeAdjusted != null) {
        View view = fragmentToBeAdjusted.getView();
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(fragmentCoordinates.getWidth(), fragmentCoordinates.getHeight());
        params.leftMargin = fragmentCoordinates.getX0();
        params.bottomMargin = fragmentCoordinates.getY0();
        view.setLayoutParams(params);
        view.requestLayout();
        return true;
    }
    return false;
}

But instead of adding and then resizing, how do I add a fragment with custom dimensions (height, width and margins) ?

like image 529
jay Avatar asked Jun 29 '16 08:06

jay


People also ask

How do you inflate a fragment?

How do you inflate a fragment? Android calls the onCreateView() callback method to display a Fragment . Override this method to inflate the layout for a Fragment , and return a View that is the root of the layout for the Fragment .

What is FragmentManager?

FragmentManager is the class responsible for performing actions on your app's fragments, such as adding, removing, or replacing them, and adding them to the back stack.

How do I attach a fragment to an activity?

Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.

What is FragmentContainerView?

FragmentContainerView is a customized Layout designed specifically for Fragments. It extends FrameLayout , so it can reliably handle Fragment Transactions, and it also has additional features to coordinate with fragment behavior.


1 Answers

You can pass desired width height and margin to fragment and assign that value while inflating the view

For example if you are using Frame layout as container for fragments then pass values with new instance method

/**
         * 
         * @param widthInDP
         * @param heightinDP
         * @param leftMarginDp
         * @param topMarginDp
         * @param rightMarginDp
         * @param bottomMarginDp
         * @param fragIndex
         * @return
         */
        public static PlaceholderFragment newInstance(int widthInDP,
                int heightinDP, int leftMarginDp, int topMarginDp,
                int rightMarginDp, int bottomMarginDp, int fragIndex) {
            PlaceholderFragment resizableFragment = new PlaceholderFragment();

            Bundle args = new Bundle();

            // Test purpose Only
            args.putInt(INDEX, fragIndex);

            // Set Width Height dynamically
            args.putInt(WIDTH, widthInDP);
            args.putInt(HEIGHT, heightinDP);

            // SetMargin
            args.putInt(LEFT_MARGIN, leftMarginDp);
            args.putInt(RIGHT_MARGIN, rightMarginDp);
            args.putInt(TOP_MARGIN, topMarginDp);
            args.putInt(BOTTOM_MARGIN, bottomMarginDp);
            resizableFragment.setArguments(args);

            return resizableFragment;
        }

And then apply them in onCreateView method. Point to note here if you are using Frame layout as container for fragments then use FrameLayout param else you will get exception.

   FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) rootView
            .getLayoutParams();

    // set width height
    params.height = dpToPx(getArguments().getInt(HEIGHT));
    params.width = dpToPx(getArguments().getInt(WIDTH));

    // substitute
    // parameters for left,top, right, bottom
    params.setMargins(dpToPx(getArguments().getInt(LEFT_MARGIN)),
            dpToPx(getArguments().getInt(TOP_MARGIN)),
            dpToPx(getArguments().getInt(RIGHT_MARGIN)),
            dpToPx(getArguments().getInt(BOTTOM_MARGIN)));
    rootView.setLayoutParams(params);  

Output :-

Orange background is my Frame layout container and all other are resized Fragments with custom margins in same container. You can also play around with LayoutParam.Gravity property to make them go left right, top, bottom , center, bottom- center, top center and so on

enter image description here

Complete code I used in sample

package com.example.fragment;

    import android.annotation.TargetApi;
    import android.graphics.Color;
    import android.os.Build;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.util.DisplayMetrics;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.FrameLayout;
    import android.widget.TextView;

    public class MainActivity extends FragmentActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            if (savedInstanceState == null) {
                getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.container,
                                PlaceholderFragment.newInstance(400, 400, 50, 50,
                                        50, 50, 1)).commit();

                getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.container,
                                PlaceholderFragment.newInstance(300, 300, 30, 30,
                                        30, 30, 2)).commit();

                getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.container,
                                PlaceholderFragment.newInstance(200, 200, 20, 20,
                                        20, 20, 3)).commit();

                getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.container,
                                PlaceholderFragment.newInstance(100, 100, 10, 10,
                                        10, 10, 4)).commit();
            }
        }

        /**
         * A placeholder fragment containing a simple view.
         */
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        public static class PlaceholderFragment extends Fragment {

            private static final String HEIGHT = "Height";
            private static final String WIDTH = "Width";
            private static final String LEFT_MARGIN = "left";
            private static final String RIGHT_MARGIN = "right";
            private static final String TOP_MARGIN = "top";
            private static final String BOTTOM_MARGIN = "bottom";

            // Test Data
            private static final String INDEX = "FragNumber";

            /**
             * 
             * @param widthInDP
             * @param heightinDP
             * @param leftMarginDp
             * @param topMarginDp
             * @param rightMarginDp
             * @param bottomMarginDp
             * @param fragIndex
             * @return
             */
            public static PlaceholderFragment newInstance(int widthInDP,
                    int heightinDP, int leftMarginDp, int topMarginDp,
                    int rightMarginDp, int bottomMarginDp, int fragIndex) {
                PlaceholderFragment resizableFragment = new PlaceholderFragment();

                Bundle args = new Bundle();

                // Test purpose Only
                args.putInt(INDEX, fragIndex);

                // Set Width Height dynamically
                args.putInt(WIDTH, widthInDP);
                args.putInt(HEIGHT, heightinDP);

                // SetMargin
                args.putInt(LEFT_MARGIN, leftMarginDp);
                args.putInt(RIGHT_MARGIN, rightMarginDp);
                args.putInt(TOP_MARGIN, topMarginDp);
                args.putInt(BOTTOM_MARGIN, bottomMarginDp);
                resizableFragment.setArguments(args);

                return resizableFragment;
            }

            public PlaceholderFragment() {
            }

            public int dpToPx(int dp) {
                DisplayMetrics displayMetrics = getActivity().getResources()
                        .getDisplayMetrics();
                int px = Math.round(dp
                        * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
                return px;
            }

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

                View rootView = inflater.inflate(R.layout.fragment_main, container,
                        false);

                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) rootView
                        .getLayoutParams();

                // set width height
                params.height = dpToPx(getArguments().getInt(HEIGHT));
                params.width = dpToPx(getArguments().getInt(WIDTH));

                // substitute
                // parameters for left,top, right, bottom
                params.setMargins(dpToPx(getArguments().getInt(LEFT_MARGIN)),
                        dpToPx(getArguments().getInt(TOP_MARGIN)),
                        dpToPx(getArguments().getInt(RIGHT_MARGIN)),
                        dpToPx(getArguments().getInt(BOTTOM_MARGIN)));
                rootView.setLayoutParams(params);

                // Test purpose Only
                switch (getArguments().getInt(INDEX)) {
                case 1:
                    rootView.setBackgroundColor(Color.MAGENTA);

                    ((TextView) rootView.findViewById(R.id.frag_index))
                            .setText("Fragment # " + getArguments().getInt(INDEX));

                    break;

                case 2:
                    rootView.setBackgroundColor(Color.GREEN);

                    ((TextView) rootView.findViewById(R.id.frag_index))
                            .setText("Fragment # " + getArguments().getInt(INDEX));

                    break;

                case 3:
                    rootView.setBackgroundColor(Color.BLUE);

                    ((TextView) rootView.findViewById(R.id.frag_index))
                            .setText("Fragment # " + getArguments().getInt(INDEX));

                    break;

                default:
                    rootView.setBackgroundColor(Color.WHITE);

                    ((TextView) rootView.findViewById(R.id.frag_index))
                            .setText("Fragment # " + getArguments().getInt(INDEX));

                    break;
                }

                return rootView;
            }
        }
    }

So technically this is doable but I didn't understand why you are trying to do this way ?

like image 137
Hitesh Sahu Avatar answered Oct 18 '22 20:10

Hitesh Sahu