View.getContext()与Activity的Context

> View.getContext()
Context context = imageView.getContext();
 if (context instanceof Activity) {
     Activity activity = (Activity)context;
       // ...
 }
  在 5.0 以下,这个 imageView.getContext() 获取到的 context 类型不是我一开始以为的 Activity 类型,而是 TintContextWrapper 类型。 控件所在的 Activity 是继承自 AppCompatActivity ,这个 context 类型的变化一定是和 v7 包里的 AppCompatActivity 有关系。
  view的context就是LayoutInflater的mContext:这个LayoutInflater的context是PhoneWindow传进去的:PhoneWindow的context就是Activity的this 。
  所有Appcompat的Activity,创建View的时候,都会对基本View做一个风格的包装,也就是说ImageView会变成AppcompatImageView。 那么实际上,imageView.context 是AppcompatImageView的getContext().发现即使context传进来是个activity,也回被包装成TintContextWrapper。那么为什么5.0以上系统,获得的还是一个Activity呢?

private static AppCompatDelegate create(Context context, Window window,
        AppCompatCallback callback) {
    final int sdk = Build.VERSION.SDK_INT;
    if (BuildCompat.isAtLeastN()) {
        return new AppCompatDelegateImplN(context, window, callback);
    } else if (sdk >= 23) {
        return new AppCompatDelegateImplV23(context, window, callback);
    } else if (sdk >= 14) {
        return new AppCompatDelegateImplV14(context, window, callback);
    } else if (sdk >= 11) {
        return new AppCompatDelegateImplV11(context, window, callback);
    } else {
        return new AppCompatDelegateImplV9(context, window, callback);
    }
}

View.getContext() 里的小秘密- https://blog.csdn.net/weixin_34380948/article/details/88029324
-- View.getContext() 如何强制转为 Activity ?
@Nullable
private Activity getActivity(@NonNull View view) {
    if (null != view) {
        Context context = view.getContext();
        while (context instanceof ContextWrapper) {
            if (context instanceof Activity) {
                return (Activity) context;
            }
            context = ((ContextWrapper) context).getBaseContext();
        }
    }
    return null;
}

> Activity等的Context
Context的两个子类分工明确,其中ContextImpl是Context的具体实现类,ContextWrapper是Context的包装类。Activity,Application,Service虽都继承自ContextWrapper(Activity继承自ContextWrapper的子类ContextThemeWrapper),但它们初始化的过程中都会创建ContextImpl对象,由ContextImpl实现Context中的方法。

-- 通常我们想要获取Context对象,主要有以下四种方法
 1:View.getContext,返回当前View对象的Context对象,通常是当前正在展示的Activity对象。
 2:Activity.getApplicationContext,获取当前Activity所在的(应用)进程的Context对象,通常我们使用Context对象时,要优先考虑这个全局的进程Context。
 3:ContextWrapper.getBaseContext():用来获取一个ContextWrapper进行装饰之前的Context,可以使用这个方法,这个方法在实际开发中使用并不多,也不建议使用。
 4:Activity.this 返回当前的Activity实例,如果是UI控件需要使用Activity作为Context对象,但是默认的Toast实际上使用ApplicationContext也可以。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
大家好,今天给大家分享一下Android里的Context的一些用法. 这里大致可以分为两种:一是传递Context参数,二是调用全局的Context. 其实我们应用启动的时候会启动Application这个类,这个类是在AndroidManifest.xml文件里其实是默认的 为了让大家更容易理解,写了一个简单的Demo.步骤如下: 第1步:新建一个Android工程ApplicationDemo,目录结构如下: 第2步:新建一个工具类ToolsUtil.java,代码如下 package com.tutor.application; import android.content.Context; import android.widget.Toast; /** * @author carlshen. * 应用的一些工具类. */ public class ToolUtils { /** * 参数带Context. * @param context * @param msg */ public static void showToast(Context context,String msg){ Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } /** * 调用全局的Context. * @param msg */ public static void showToast(String msg){ Toast.makeText(MainApplication.getContext(), msg, Toast.LENGTH_SHORT).show(); } } 第3步:新建一个View命名为MainView.java就是我们Activity现实的View.代码如下: package com.tutor.application; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; /** * @author carlshen. * 自定义的MainView. */ public class MainView extends FrameLayout implements View.OnClickListener{ private Context mContext; private Activity mActivity; /** * 参数Button. */ private Button mArgButton; /** * 全局Button. */ private Button mGlobleButton; /** * 退出Button. */ private Button mExitButton; public MainView(Context context){ super(context); setupViews(); } public MainView(Context context, AttributeSet attrs) { super(context, attrs); setupViews(); } private void setupViews(){ //获取View的上下文. mContext = getContext(); //这里将Context转换为Activity. mActivity = (Activity)mContext; LayoutInflater inflater = LayoutInflater.from(mContext); View v = inflater.inflate(R.layout.main, null); addView(v); mArgButton = (Button)v.findViewById(R.id.arg_button); mGlobleButton = (Button)v.findViewById(R.id.glo_button); mExitButton = (Button)v.findViewById(R.id.exit_button); mArgButton.setOnClickListener(this); mGlobleButton.setOnClickListener(this); mExitButton.setOnClickListener(this); } public void onClick(View v) { if(v == mArgButton){ ToolUtils.showToast(mContext, "我是通过传递Context参数显示的!"); }else if(v == mGlobleButton){ ToolUtils.showToast("我是通过全局Context显示的!"); }else{ mActivity.finish(); } } } 这里MainView.java使用的布局main.xml代码如下: <?xml version="1.0" encoding="utf-8"?> 第4步:修改ApplicationDemoActivity.java,代码如下: package com.tutor.application; import android.app.Activity; import android.os.Bundle; public class ApplicationDemoActivity extends Activity { private static Context aContext; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MainView mMainView = new MainView(this); setContentView(mMainView); aContext = getApplicationContext(); } /**获取Context. * @return */ public static Context getContext(){ return aContext; } } 第5步:运行上述工程效果如下:

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值