Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a context in Android created? What is the purpose of ContextThemeWrapper?

I'm helping put together this page: What is a context?

To help illustrate how components are related to a Context, I created this diagram from looking through the framework source code:

Context Subclasses

After digging around a bit, I had the following questions:

  1. What creates a Context and what concrete classes are used? The base Context class itself is an abstract class, which requires almost all of its methods to be implemented. And a ContextWrapper, when instantiated, requires a Context instance to be passed in as it's base context, so there must be at least one concrete Context class.
  2. I understand that the ContextWrapper and its subclasses utilize the wrapper/decorator pattern to add functionality to the base Context class as needed. What is the purpose of the ContextThemeWrapper? It overrides a few methods, but if it's wrapping a base Context, why not just delegate the calls to the base Context? For example, the Activity class extends ContextThemeWrapper, which provides a specific implementation for getTheme() and setTheme(). Why?

The Android developer java docs are a bit vague. E.g., ContextWrapper

like image 711
orangemako Avatar asked Jul 16 '15 17:07

orangemako


People also ask

What is ContextThemeWrapper class in Android?

A ContextThemeWrapper allows us to modify or overlay the theme of another context.

How does context work in Android?

Definition. it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application).

What is the use of ContextWrapper?

Android provides a ContextWrapper class that is created around an existing Context using: ContextWrapper wrapper = new ContextWrapper(context); The benefit of using a ContextWrapper is that it lets you “modify behavior without changing the original Context”.

How many types of context are there in Android?

There are essentially two types of context : Application Context. Activity Context.


1 Answers

Answering #2:

ContextThemeWrapper adds theming support to a Context, otherwise you can't apply any theme to the Views you create. That's why Activity layouts support themes while widget layouts don't, for example. You can also create a ContextThemeWrapper yourself to override the current theme with another one.

like image 182
BladeCoder Avatar answered Nov 15 '22 13:11

BladeCoder