如何在代码中获取和设置样式属性?

时间:2018-09-09 11:54:55

标签: android android-layout android-styles

假设以下代码:

          <MyCustomComponent
            style="@style/Base.TextAppearance.AppCompat.Headline"
            android:padding="@dimen/padding_default"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

在自定义组件中,我有一个EditText,我需要根据布局中的@style/Base.TextAppearance.AppCompat.Headline属性在Java代码中将其style属性设置为style。我该怎么办?

我正在创建一个自定义组件,因此我还需要知道组件的用户在布局中选择了哪种样式。 是否可以通过AttributeSet使用?如果是,请告诉我如何?

2 个答案:

答案 0 :(得分:1)

要以编程方式设置TextView的样式,您必须具有继承TextAppearance样式的样式,并且可以使用以下代码来应用它:

if (Build.VERSION.SDK_INT < 23) { textView.setTextAppearance(context,android.R.style.TextAppearance_Small); } else { textView.setTextAppearance(android.R.style.TextAppearance_Small); }

答案 1 :(得分:0)

在style.xml中定义自定义样式,如下所示:

<style name="MyHeadlineTextAppearance" parent="Base.TextAppearance.AppCompat.Headline"/>

然后将其设置为您的TextView,如下所示:

textView.setTextAppearance(context, R.style.MyHeadlineTextAppearance);
相关问题