Search code examples
androidlayoutandroid-linearlayoutmargin

A lot of spacing between views and margin doesn't do the stuff


I have a HorizontalScrollView with a vertical LinearLayout in it. There I add some custom views of the same type. By default there is a lot of spacing between the views. So I guessed I have to set the margin of my views to 0 or something. But there ist absolutely no result.
First I tried to change the margin in the xml

    <gui.CardUi
     android:id="@+id/cardUi"
     android:layout_width="wrap_content"
     android:layout_height="match_parent"
     android:layout_margin="0dp"
   </gui.CardUi>

Than I tried it to change the margin in code:

    private void setMargins ( int left, int top, int right, int bottom) {
     if (getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) getLayoutParams();
        p.setMargins(left, top, right, bottom);
        requestLayout();
     }
    }

 setMargins(0, 0, 0, 0);

Not sure if the info is important but I add the views programmatically with LayoutInflater.


Solution

  • Your margins would not be set because of the way you inflate the views. I guess you used such a way:

    View child = getLayoutInflater().inflate(R.layout.mylayout, null);
    

    The point is when you want to inflate a view and add it to another view, You should inform the inflater about the container view (in your example Linear layout). So your layout parameter such as margins and weight and gravity would be set correctly. So use this method instead:

    View child = getLayoutInflater().inflate(R.layout.child, item, false);
    

    There is no need to add margin in your code.