2016-06-29 8 views
12

Derzeit füge ich ein Fragment mit dem folgenden Code hinzu.Android - Fragment mit benutzerdefinierten Dimensionen hinzufügen

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

Der folgende Code dient zum Ändern der Größe des hinzugefügten Fragments.

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

Aber anstatt das Hinzufügen und dann Ändern der Größe, wie füge ich ein Fragment mit benutzerdefinierten Dimensionen (Höhe, Breite und Margen)?

Antwort

6

Sie können gewünschte Breite Höhe und Rand passieren diesen Wert fragmentieren, und weisen gleichzeitig die

Zum Beispiel Ansicht Aufblasen, wenn Sie Rahmenlayout als Behälter verwenden für Fragmente dann neue Instanz Methode

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

Und dann wenden Sie sie in onCreateView Methode. Beachten Sie hier, wenn Sie Frame-Layout als Container für Fragmente verwenden, dann verwenden Sie FrameLayout param sonst erhalten Sie eine Ausnahme.

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

Ausgang: -

orange Hintergrund ist mein Frame layout Container und alle anderen Fragments mit benutzerdefinierten Margen in demselben Behälter der Größe verändert werden. Sie können auch mit LayoutParam.Gravity Eigenschaft spielen, um sie links rechts, oben, unten, Mitte, Bottom-Center, oben in der Mitte gehen lassen und so weiter

enter image description here

kompletten Code, den ich in der Probe verwendet

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

Also technisch ist das machbar, aber ich habe nicht verstanden, warum Sie versuchen, so zu tun?

+2

Ich habe gerade diese Lösung gedruckt =) Vergessen Sie nicht, LayoutParams sollte den Typ Ihres Containers haben. – Alexander

+0

Ich denke, dann zeige ich in die richtige Richtung. –

+0

Ja, es ist eine gute Lösung. Aber ich habe Builder anstelle von newInstance verwendet. – Alexander

-1

Sie können die Abmessungen in der Containeransicht R.id.fragment_container in Ihrem Fall festlegen und das Fragment den gesamten verfügbaren Speicherplatz belegen.

+0

Ich brauche den Container, um mehrere Fragmente enthalten zu können. Wenn die Größenänderung von Fragmenten möglich ist, warum kann ich die Größe während der Addierzeit nicht selbst festlegen? – jay

2

Sie können es tun, indem LayoutParams in Fragments onCreateView, wie diese Angabe -

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

Warum Ihre eigene Viewgroup nicht zu versuchen, zu machen? Es liegt in der Verantwortung von ViewGroup, die Position von Kindern in onLayout() und seine Größe in onMeasure() anzupassen. Erweitern Sie einfach die benötigten Viewgroup- und Override-Methoden mit der gewünschten Logik und den gewünschten Einschränkungen.

2
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(); 
+0

Ich habe genau das gleiche getan, um ein neues Fragment hinzuzufügen, aber ich brauchte einen Weg, um die Dimensionen des Fragments dynamisch festzulegen. Hiteshs Lösung war eine wirklich gute Möglichkeit, das zu erreichen. – jay

Verwandte Themen