【问题标题】:Android Style Custom ViewGroupAndroid 风格自定义 ViewGroup
【发布时间】:2014-02-13 19:03:54
【问题描述】:

我有一个自定义视图组,其中包含几个简单的视图。如何设置我的视图组的样式,以便某些属性到达某些子元素?例如,在下面的示例中,我如何创建允许轻松更改文本大小、颜色等的样式。如果可能的话,我想在 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>

如果此视图的样式始终相同,这不是问题,但我想在不同的情况下使用不同的样式,这样我的应用程序的某些区域可以更大,而在其他区域更小.

提前致谢!

【问题讨论】:

  • 尝试为每个底层子视图制作一些自定义属性(格式参考),您将在CustomViewGroup 上使用这些属性。然后为这些属性分配适当的样式,并在CustomViewGroup 的构造函数中将它们应用到正确的子级。
  • 感谢@Luksprog,这让我走上了正确的道路。如果你想看看我是怎么做的,请参阅下面的答案

标签: android android-view android-styles


【解决方案1】:

根据@Luksprog 的评论,我能够走上一条通往不那么完美但不够丑陋的解决方案的道路。

因为我没有在我的 ViewGroup 构造函数中创建和添加视图并且是从 xml 文件中膨胀的,所以我不能只添加引用样式的属性(请参阅this)。所以我最终创建了一个枚举属性,它可以在我想要的这个视图的各种样式之间切换。然后在构造函数中,我根据这个属性膨胀了不同的布局(样式在 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;
            }

            ...
        }
    }

这又不是最优雅的解决方案,但它对我有用,我现在可以很容易地更新样式,而无需更改一堆文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多