Context的使用(Using Context)

Context用于获取application状态信息。为Activities,Fragments,Services访问resource files,images,themes,styles以及external directory location。还能访问android内建服务(services),例如layout inflation,keyboard,查找content providers(内容提供器)。
在许多情况下需要context的时候,我们只是简单的在当前activity实例中进行传递。在另外情况下,在activity创建的对象里,例如adapters或者fragment,我们需要在activity实例的对象里进行传递。而在activity外(例如application或者service)时,我们可以使用“application”context来代替。

明确创建一个component

// Provide context if MyActivity is an internal activity.
Intent intent = new Intent(context, MyActivity.class);
startActivity(intent);

需要两个信息:
1、package name,表明包含该component的application;
2、该component的完整java类名。

创建一个View

TextView textView = new TextView(context);

context包含以下view所需的信息:
1、device的screen size和尺寸,用于dp,sp和像素之间转换;
2、样式属性;
3、onClick属性的activity参考

inflating an XML Layout File

为了inflate一个XML Layout文件进入memory,使用context取LayoutInflater。(???)

// The context contains a reference to the main Looper, 
// which manages the queue for the application's main thread.
Intent broadcastIntent = new Intent("custom-action");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

恢复系统服务

从application发送notification,需要NotificationManager系统服务:

// Context objects are able to fetch or start system services.
NotificationManager manager = 
    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

int notificationId = 1;

// Context is required to construct RemoteViews
Notification.Builder builder = 
    new Notification.Builder(context).setContentTitle("custom title");

notificationManager.notify(notificationId, builder.build());

application Vs Activity Context

<application
       android:allowBackup="true"
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme" >
       <activity
           android:name=".MainActivity"
           android:label="@string/app_name"
           android:theme="@style/MyCustomTheme">

Adapters

Array Adapter
当ListView构建adapters时,通常在layout inflation中调用getContext()。

if (convertView == null) {
        convertView = 
            LayoutInflater
                .from(getContext())
                .inflate(R.layout.item_user, parent, false);
     }

> If you instantiate the ArrayAdapter with the application context,however, you are likely to notice that the themes/styles are not beingapplied. For this reason, make sure you are passing in the Activitycontext in these cases.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值