There is a file with style, its contents:

<style name="myStyle"> <item name="android:layout_height">wrap_content</item> <item name="android:layout_width">wrap_content</item> <item name="android:layout_marginTop">10dp</item> </style> 

I create a new textView in the java file: TextView tv = new TextView ();

How to programmatically apply the specified style to the created View? What methods to use?

  • 3
    I think the question is more than deployed - SergeyCFMM

3 answers 3

 final Context contextThemeWrapper = new ContextThemeWrapper(context, R.style.myStyle); View view = new View(contextThemeWrapper); 
  • tried your version, not stylized ( - dramf

Define in res / values ​​/ attrs.xml:

 <attr name="customTextViewStyle" format="reference"/> 

In 'res / values ​​/ style.xml' add to your topic:

 <style name="AppBaseTheme" parent="android:Theme.Light"> <item name="@attr/customTextViewStyle"> @style /myStyle</item> </style> 

Use this:

 new TextView (context, null, android.R.attr.customTextViewStyle); 

    I once killed a couple of days to find an answer. I did not find a solution specifically for this approach. but found a slightly different approach:
    Create a layout with the desired View in the root, apply a style to it in this layout file.
    When you need to create a View programmatically, use code like this:

     TextView textView = (TextView) getLayoutInflater().inflate(R.layout.styled_text_view, null); 

    Well and, just in case, an example styled_text_view.xml :

     <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/featured" style=" @style /MenuItemTextStyle" /> 
    • @metalurgus try my solution, which I gave in the answer - andreich