在Android编程中,Context
类到底是什么,它有什么用?
我在 developer site 上读到过它, 但我无法清楚地理解它。
最佳答案
简单来说:
顾名思义,它是应用程序/对象当前状态的上下文。它让新创建的对象了解发生了什么。通常,您调用它是为了获取有关程序另一部分( Activity 和程序包/应用程序)的信息。
您可以通过调用 getApplicationContext()
、getContext()
、getBaseContext()
或 this
获取上下文>(当在从 Context
扩展的类中时,例如 Application、Activity、Service 和 IntentService 类)。
上下文的典型用途:
创建新对象: 创建新的 View 、适配器、监听器:
TextView tv = new TextView(getContext()); ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
访问标准公共(public)资源: LAYOUT_INFLATER_SERVICE、SharedPreferences 等服务:
context.getSystemService(LAYOUT_INFLATER_SERVICE) getApplicationContext().getSharedPreferences(*name*, *mode*);
隐式访问组件: 关于内容提供者、广播、 Intent
getApplicationContext().getContentResolver().query(uri, ...);
关于android - Android 上的 'Context' 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4799614/