I have theme that specifies textColor for TextView as red.
I am using LayoutInflater to instantiate TextView. The problem is that styles are not applied to TextView
Never use an Application Context to inflate views, because styling doesn't work with this context. Always use an Activity's context when playing with views. The only exception is when you need to create RemoteViews from a Service.
More info about the different types of Contexts and their capabilities can be found in this excellent article.
Solution # 1
The inflate method accepts optional 'ViewGroup root' argument:
public View inflate (int resource, ViewGroup root, boolean attachToRoot)
If we have value to pass as 'root' parameter, than hence we can use it to get 'activity context' from where we can get correct LayoutInflater:
ViewGroup root > activity context > LayoutInflater
So my code could be:
private void add(LinearLayout container) {
LayoutInflater inflater = getInflater(container.getContext());
inflater.inflate(R.layout.my_template, container, true);
}
Solution # 2
Just tried to set Application Context theme programmatically, and it works:
getApplicationContext().setTheme(R.style.MyTheme);
I think it was logical to expect this markup:
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:theme="@style/MyTheme"
>
to set it automatically, but it does not.
I usually come across this issue on inflating a custom view. Here is what I personally do to keep the same theme of the activity in the CustomView
public class CustomView extends ViewGroup{
public CustomView (Context context) {
super(context);
init(context);
}
public CustomView (Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CustomView (Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
@TargetApi(21)
public CustomView (Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
private void init(Context context) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = mInflater.inflate(R.layout.review_list_item, this, true);
//rest of view initialization
}
}
You probably use a context that isn't one that has a theme.
To solve it, use something as such:
val inflater= LayoutInflater.from(context).cloneInContext(ContextThemeWrapper(context, R.style.some_activity_theme))
You can read more about this here