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.

  • Google Play shows the implicit READ_EXTERNAL_STORAGE permission
  • Android onConfigurationChanged not being called
  • How can I prevent wild scrolling when a fixed position text input form field gains focus?
  • Create PDF / Word (Doc) file within app
  • Last Accessed Time of any file in Android
  • Getting web fonts to work with phonegap and android - how?
  • 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) ?

    Related posts:

    Android Gradle How to build for Android Google APIs 4.2.2 not for Android 4.2.2
    Android: How to achieve the glow effect when long-pressing a list item?
    iPhone or Android apps that use SMS based authentication?
    How do I get multiple icons to launch different activities in one application?
    Saving Fragment state in ViewPager
    Update a listview in a fragment from a broadcast receiver
  • In-line annotations give syntax errors
  • Android Intent.FLAG_ACTIVITY_SINGLE_TOP AND Intent.FLAG_ACTIVITY_CLEAR_TOP
  • Does Android support layout inheritance (similar to Django templates)?
  • Android SQLiteOpenHelper cannot open database file
  • simple example on how to use SwipeRefreshLayout with ListView
  • Chrome devTools no longer seeing USB devices for debugging
  • 5 Solutions collect form web for “Android – add fragment with custom dimensions”

    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 ?

    You can do it by specifying LayoutParams in fragment’s onCreateView, like this –

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.so_demo_frag,container,false);
        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 400);
        v.setLayoutParams(p);
        return v;
    }
    
    Just add it with framelayout in your mainActvity and add your fragment like this: 
    
            <FrameLayout
                android:id="@+id/playfragment"
                android:layout_width="match_parent"
                android:layout_height="30dp" />
    
    
     FragmentPlay frg2 = new FragmentPlay();//create the fragment instance for the top fragment
            FragmentManager manager = getSupportFragmentManager();//create an instance of fragment manager
            FragmentTransaction transaction = manager.beginTransaction();//create an instance of Fragment-transaction
            transaction.add(R.id.playfragment, frg2, "Frag_Top_tag");
            transaction.commit();
    

    Why not to try making your own ViewGroup? It is ViewGroup responsibility to adjust childs position in onLayout() and its sizes in onMeasure(). Just extend needed viewgroup and override methods with the logic and constraints your want.

    You can set the dimensions on the container view, R.id.fragment_container in your case, and let the fragment take up all the available space.

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.