Android: añadir fragmento con dimensiones personalizadas

Actualmente, estoy agregando un fragmento usando el código siguiente.

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(); } 

El siguiente código es para cambiar el tamaño del fragmento añadido.

 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; } 

Pero en lugar de agregar y luego cambiar el tamaño, ¿cómo agrego un fragmento con dimensiones personalizadas (altura, ancho y márgenes)?

Puede pasar altura de ancho deseada y margen para fragmentar y asignar ese valor mientras infla la vista

Por ejemplo, si está utilizando Frame layout como contenedor para fragmentos y luego pasar valores con el método de nueva instancia

 /** * * @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; } 

Y luego aplicarlos en el método onCreateView . Punto a tener en cuenta aquí si está utilizando Frame layout como contenedor para fragmentos y luego use FrameLayout param más obtendrá excepción.

  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); 

Salida: –

Fondo naranja es mi contenedor de Frame layout y todos los demás son redimensionados Fragments con márgenes personalizados en el mismo contenedor. También puedes jugar con la propiedad LayoutParam.Gravity para hacerlos ir a la izquierda, a la derecha, arriba, abajo, centro, centro inferior, centro superior y así sucesivamente

Introduzca aquí la descripción de la imagen

Código completo que usé en la muestra

 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; } } } 

Así que técnicamente esto es factible, pero yo no entendía por qué estás tratando de hacer de esta manera?

Usted puede hacerlo especificando LayoutParams en el onCreateView del fragmento, como esto –

 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(); 

¿Por qué no intentar hacer su propio ViewGroup? Es responsabilidad de ViewGroup ajustar la posición de childs en onLayout () y sus tamaños en onMeasure (). Simplemente extienda los métodos necesarios de viewgroup y override con la lógica y las restricciones que desea.

Puede configurar las dimensiones en la vista de contenedor, R.id.fragment_container en su caso y dejar que el fragmento ocupe todo el espacio disponible.

  • Toast dentro del método onClick en Fragment
  • Deshabilitar la paginación de ViewPager cuando el reciclador de niños se desplaza al último elemento
  • null array error en la aplicación de google maps V2 android
  • Indexación de aplicaciones para aplicaciones con una sola actividad principal
  • Actionbarsherlock + tabs + multi fragmentos?
  • Pruebas funcionales de Android Espresso con fragmentos
  • CoordinatorLayout + ActionBar + Fragmentos
  • ¿Puedo añadir AnimationListener para la traducción Fragment?
  • Bauerca drag-sort-listview ejemplo sencillo
  • Cómo ocultar la barra de herramientas en un ViewPager al usar Scrolling RecyclerView?
  • Solución para el error de Android relacionado con setRetainInstance (true)
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.