谈谈Android里的Context的使用

时间:2015-10-29 08:44:52
【文件属性】:
文件名称:谈谈Android里的Context的使用
文件大小:153KB
文件格式:ZIP
更新时间:2015-10-29 08:44:52
Android Context 大家好,今天给大家分享一下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"?>

网友评论

  • 是个一个项目文件,我还以为是一个文档性质的说明呢。
  • 很受益,嘻嘻
  • 这个例子很好,很实用!