二、Context使用的示例" />
当前位置: 代码迷 >> Android >> 二、Context使用的示例
  详细解决方案

二、Context使用的示例

热度:47   发布时间:2016-04-28 00:14:48.0
Android基础知识_Context的理解及使用

一、Context 的作用

1.API 类的继承关系


2.API 类的概述

   一个关于应用程序环境的全局信息接口。这是一个抽象类,它的实现是由Android系统提供的。它允许访问应用特有的资源和类,也可以向上调用应用级操作例如运行Activity、广播和接收Intent意图等。

二、Context使用的示例

   示例工程LearnContext的MainActivity.java代码如下:
package com.example.learncontext;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.widget.ImageView;import android.widget.TextView;public class MainActivity extends Activity {//	private TextView textView;		@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);				/* 示例① */		/* TextView(Context context), 传入参数至少是一个Context, 便于访问资源、全局信息 *///		textView = new TextView(this);////		textView.setText("Hello Android!");				/* setText(int resid), 传入资源ID		 * Android 访问全局信息必须使用Context		 * *///		textView.setText(R.string.hello_world);//		setContentView(textView);//		System.out.println(getResources().getText(R.string.hello_world));				/* 示例②: 获取图标资源 */		ImageView imageView = new ImageView(this);		imageView.setImageResource(R.drawable.ic_launcher);		setContentView(imageView);	}	@Override	public boolean onCreateOptionsMenu(Menu menu) {		// Inflate the menu; this adds items to the action bar if it is present.		getMenuInflater().inflate(R.menu.main, menu);		return true;	}}
   解除相应部分注释,运行示例工程进一步体验Context访问全局信息的功能。

版权声明:本文为博主原创文章,未经博主允许不得转载。

  相关解决方案