使用Context创建一个View需要注意的地方

如果我们在java代码中创建一个View,那么需要在View的构造方法中传一个Context,Application和Activity都是Context的子类,关于使用Application和Activity的创建一个View,google的引导教程是这样解释的:

It is possible to get the Context for the Application, but it is incorrect to use that context for creating UI, because it does not have the correct theme information. Instead, use the Context object for the Activity instead. For example, if you are retrieving resources for your activity, you should do so from the Activity context, not the Application context.

就是说Application 这个Context没有携带正确的主题信息。我们应该使用Activity的Context。比如想取得Activity的资源就应该通过Activity context,而不是Application Context。 这是我做的一个小测试

//通过activity创建一个View
RadioButton button1 = new RadioButton(this);
button1.setLayoutParams(params);
button1.setText("RadioButton created by activity");

//通过Application创建一个View
RadioButton button2 = new RadioButton(getApplicationContext());
button2.setLayoutParams(params);
button2.setText("RadioButton created by Application");
linerLayout.addView(button1);
linerLayout.addView(button2);
复制代码

这2个RadioButton分别通过Activity和Application创建。最后的看看结果:

可以发现两个button选中时的颜色不一样,这是因为Activity创建的RadioButton携带有AppTheme中的主题信息。

@color/colorPrimary
@color/colorPrimaryDark
@color/colorAccent
复制代码

随便补上一张详细的Context使用场景

  1. 启动Activity在这些类中是可以的,但是需要创建一个新的task。一般情况不推荐。
  2. 在这些类中去layout inflate是合法的,但是会使用系统默认的主题样式,如果你自定义了某些样式可能不会被使用。
  3. 在receiver为null时允许,在4.2或以上的版本中,用于获取黏性广播的当前值。(可以无视)

注:ContentProvider、BroadcastReceiver之所以在上述表格中,是因为在其内部方法中都有一个context用于使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值