Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain layout attributes on merged custom android view?

I'm trying to replace a set of views with a custom composite view that is supposed to do exactly the same. Specifically I frequently repeat the following layout:

<LinearLayout style="@style/customLayoutStyle">
  <Button style="@style/customButtonStyle" />
  <TextView style="@style/customTextViewStyle" />
</LinearLayout>

My goal is to replace this block by a single <Highlighter />.

To this end I define in res/layout/highlighter.xml something like

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/customLayoutStyle">
    <Button android:id="@+id/btnHighlighter" style="@style/customButtonStyle" />
    <TextView android:id="@+id/lblHighlighter" style="@style/customTextViewStyle" />    
</merge>

And in my custom view I have something like

public class Highlighter extends LinearLayout {
    public Highlighter(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflate(context, R.layout.highlighter, this);
    }
}

This mostly works, but it seems some of the layout parameters of the <merge> tag are ignored. This screenshot illustrates what seems to be wrong. The 3 images on the bottom row are aligned correctly, using 3x the LinearLayout block I'm trying to replace. Only the top-left image uses the custom view. My guess is that the layout parameters for padding and layout_weight are lost. Am I doing something wrong, or do I need a workaround?

like image 996
Frank Razenberg Avatar asked Feb 09 '13 12:02

Frank Razenberg


People also ask

How to include layout in another layout Android?

To efficiently re-use complete layouts, you can use the <include/> and <merge/> tags to embed another layout inside the current layout. Reusing layouts is particularly powerful as it allows you to create reusable complex layouts. For example, a yes/no button panel, or custom progress bar with description text.


1 Answers

You're right about the parameters being lost. To workaround this you can put the style definition for Highlighter in the layout where you define the Highlighter.

E.g.

<yournamespace.Highlighter 
    style="@style/customLayoutStyle"
/>
like image 170
nmw Avatar answered Nov 16 '22 03:11

nmw