Android Style Custom ViewGroup

时间:2014-02-13 19:03:54

标签: android android-view android-styles

我有一个包含几个简单视图的自定义视图组。如何设置我的视图组的样式,以便某些属性到达某些子元素?例如,在下面的示例中,如何创建允许轻松更改文本大小,颜色等的样式。如果可能的话,我想在CustomViewGroup上设置xml样式。我可以在创建样式时指定ID,以便特定元素获得它吗?

使用示例:

<com.example.CustomViewGroup
    android:id="@+id/custom"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

视图组的XML:     

    <TextView
        android:id="@+id/valueTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView 
        android:id="@+id/descriptionTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/valueTextView"
        android:layout_alignLeft="@id/valueTextView"
        android:layout_marginTop="-4dip"
        android:layout_marginLeft="26dip"/>


</RelativeLayout>

如果此视图的样式在整个时间内都是相同的,这不是问题,但我想在不同的情况下使用不同的样式,所以我可以让它在我的应用程序的某些区域更大但在其他区域更小

提前致谢!

1 个答案:

答案 0 :(得分:0)

根据@Luksprog的评论,我能够走上一条通向不那么完美但又不够丑陋的道路的道路。

由于不是在我的ViewGroup构造函数中创建和添加视图并且从xml文件中膨胀,我不能只添加引用样式的属性(请参阅this)。所以我最终创建了一个enum属性,可以在我想要的视图之间切换各种样式。然后在构造函数中,我根据此属性对不同的布局(在xml中设置样式)进行了膨胀。

示例:

    public CustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context, attrs, defStyleAttr);
    }

    private void initialize(Context context, AttributeSet attrs, int defStyleAttr) {
        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomViewGroup, defStyleAttr, 0);

            int style = a.getInt(R.styleable.CustomViewGroup_styleType, 0);
            switch (style) {
                case 0:
                    View.inflate(context, R.layout.custom_view_group_small, this);
                    break;
                case 1:
                    View.inflate(context, R.layout.custom_view_group_large, this);
                    break;
                default:
                    View.inflate(context, R.layout.custom_view_group_large, this);
                    break;
            }

            ...
        }
    }

同样不是最优雅的解决方案,但它适用于我,我现在可以非常轻松地更新样式,而无需更改大量文件。

相关问题