Android 使用<;合并>;带有自定义复合组件的标记

Android 使用<;合并>;带有自定义复合组件的标记,android,merge,custom-controls,padding,Android,Merge,Custom Controls,Padding,下面是一个扩展RelativeLayout并从xml扩展特定布局的示例: public class MyCustomView extends RelativeLayout { public MyCustomView(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater.from(context).inflate(R.layout.my_custom_view

下面是一个扩展
RelativeLayout
并从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);
        // ...
    }
}
布局xml使用
标记(从视图层次结构中删除不必要的层,yada-yada-yada):


...
。。。我在其他布局中使用自定义视图,如下所示:

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

自定义视图中的所有内容都被完美地布置,但是应该围绕整个内容的20dip填充没有应用。如果我把它放在
标签上,它似乎也不起作用。当然,缺少填充物让它看起来非常糟糕。我应该把
android:padding=“20dip”
属性放在哪里才能应用它


最简单的方法可能就是让我的
MyCustomView
扩展
FrameLayout
,并用
替换
标记-但这牺牲了Romain Guy非常重视的整个“保持视图层次结构浅化”的东西:)

现在我使用一种变通方法来编程设置填充。并寻找可能更好的解决方案

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

这个对我有用。您可以在dimen.xml上定义一个维度资源,并使用context.getResources().getDimensionPixelSize(R.dimen.desired\u padding\u id)来代替您的小方法。您曾经使用过这个方法吗?我尝试在使用视图时(在更大的布局中)手动添加填充,但希望找到一个“干”er解决方案。
// 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() );