Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding lost using <merge> tag with Custom Compound Component

Here's a custom compound component that extends RelativeLayout and inflates a particular layout from xml:

public class MyCustomView extends RelativeLayout {
    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.my_custom_view, this);
        // ...
    }
}

The layout xml uses the <merge> tag (removes unnecessary layer from the view hierarchy, yada yada yada):

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageView android:layout_width="wrap_content" 
               android:layout_height="wrap_content"  ... />

    <TextView  android:layout_width="wrap_content" 
               android:layout_height="wrap_content"  ... />
    ...
</merge>

... and I use the custom view in other layouts like this:

<com.example.MyCustomView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="20dip" />

Everything within the custom view is immaculately laid out, but the 20dip padding supposed to surround the entire thing is not applied. It doesn't seem to work if I put it on the <merge> tag either. The lack of padding makes it look completely awful of course. Where am I supposed to put the android:padding="20dip" attribute to get it applied?

The easiest thing might just be to make my MyCustomView extend FrameLayout, and replace the <merge> tag with a <RelativeLayout> - but that sacrifices the whole 'keeping the view hierarchy shallow' thing that Romain Guy takes so seriously :)

like image 919
Roberto Tyley Avatar asked Jun 04 '11 09:06

Roberto Tyley


1 Answers

Now I use a workaround to set paddings programmatically. And looking for probably better solution.

// Inflate the view from the layout resource.
LayoutInflater li = LayoutInflater.from( context );
View root = li.inflate( R.layout.article_head, this, true );
int padding = convertDip2Pixels( context, 8 );
root.setPadding( padding, padding, padding, padding );        

public static int convertDip2Pixels( Context context, int dip ) {
    return (int)TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
            dip, context.getResources().getDisplayMetrics() );
like image 69
Vlad Kuts Avatar answered Oct 21 '22 05:10

Vlad Kuts