Theme/Style is not applied when inflater used with ApplicationContext

前端 未结 4 1911
挽巷
挽巷 2020-11-28 10:40

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

4条回答
  •  渐次进展
    2020-11-28 10:47

    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:

    
    

    to set it automatically, but it does not.

提交回复
热议问题