a.toraby
a.toraby

Reputation: 3391

How to get and set style attribute in code?

Suppose the following code:

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

In the custom component I have an EditText which I need to set its style attribute to @style/Base.TextAppearance.AppCompat.Headline in java code, according to the style attribute in the layout. How can I do that?

I am creating a custom component therefore I also need to know which style has been selected in layout by user of my component. Is it available through AttributeSet? If yes please let me know how?

Upvotes: 0

Views: 251

Answers (2)

Amiir Kalantari
Amiir Kalantari

Reputation: 126

For styling TextViews programmatically, you must have a style inheriting a TextAppearance style, and you can apply it using the following code:

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

Upvotes: 1

aminography
aminography

Reputation: 22832

Define a custom style in style.xml like this:

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

Then set it to your TextView as below:

textView.setTextAppearance(context, R.style.MyHeadlineTextAppearance);

Upvotes: 0

Related Questions