Add Style after creating a View programmatically

前端 未结 1 1306
梦谈多话
梦谈多话 2021-01-06 18:26

The Title says it all, hopefully.

1) I create a View programmatically:

RelativeLayout rl = new RelativeLayout(this);

2) I want to a

1条回答
  •  Happy的楠姐
    2021-01-06 19:04

    You can't apply a style after constructing a view. The correct way to do this is to use the 4-argument constructor on Android 5.0+ or to create a theme attribute that references your style and use the 3-argument constructor.

    // Works on versions prior to Android 5.0
    RelativeLayout rl = new RelativeLayout(this, null, R.attr.myRelativeLayoutStyle);
    
    // Works on Android 5.0 and above
    RelativeLayout r2 = new RelativeLayout(this, null, 0, R.style.MyRelativeLayout);
    

    res/values/attrs.xml:

    
    
        
        ...
    

    res/values/styles.xml:

    
    
        
        ...
    

    res/values/themes.xml: