如何在合并的自定义android视图上维护布局属性?

Fra*_*erg 7 android android-layout android-xml android-view

我试图用应该做的完全一样的自定义复合视图替换一组视图。具体来说,我经常重复以下布局:

<LinearLayout style="@style/customLayoutStyle">
  <Button style="@style/customButtonStyle" />
  <TextView style="@style/customTextViewStyle" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

我的目标是用一个替换该块<Highlighter />

为此,我在res / layout / highlighter.xml中定义了类似的内容

<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>
Run Code Online (Sandbox Code Playgroud)

在我的自定义视图中,我有类似

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

这通常可行,但是似乎<merge>忽略了标签的某些布局参数。此屏幕截图说明了似乎有问题的地方。使用我尝试替换的LinearLayout块的3倍,最下面一行的3张图像已正确对齐。仅左上方的图像使用自定义视图。我的猜测是padding和layout_weight的布局参数丢失了。我是在做错什么,还是需要解决方法?

nmw*_*nmw 5

您对丢失的参数是正确的。要解决此问题,可以将荧光笔的样式定义放在定义荧光笔的布局中。

例如

<yournamespace.Highlighter 
    style="@style/customLayoutStyle"
/>
Run Code Online (Sandbox Code Playgroud)

  • 这对我来说不是很令人满意,因为我需要在需要自定义视图的所有地方重复这些操作,即使它们是我的自定义视图所固有的。我想除了在我的自定义视图构造函数中手动设置它们外,别无选择 (5认同)