Android开发

安卓Android Context类实例详解

本文主要是介绍安卓Android Context类实例详解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.例如下面的代码片段,Toast类的第一个参数接受一个Context对象:

@Override 
 protected Dialog onCreateDialog(int id) { 
 switch (id) { 
 case 0: 
 
 Builder builder = new AlertDialog.Builder(this); 
 builder.setIcon(R.drawable.ic_launcher); 
 builder.setTitle("This is a dialog with some simple text..."); 
 builder.setPositiveButton("OK", 
  new DialogInterface.OnClickListener() { 
  public void onClick(DialogInterface dialog, 
  int whichButton) { 
  Toast.makeText(getBaseContext(), "OK clicked!", 
   Toast.LENGTH_SHORT).show(); 
  } 
  }); 
 
 builder.setNegativeButton("Cancel", 
  new DialogInterface.OnClickListener() { 
  public void onClick(DialogInterface dialog, 
  int whichButton) { 
  Toast.makeText(getBaseContext(), "Cancel clicked!", 
   Toast.LENGTH_SHORT).show(); 
  } 
  }); 
 
 builder.setMultiChoiceItems(items, itemsChecked, 
  new DialogInterface.OnMultiChoiceClickListener() { 
  public void onClick(DialogInterface dialog, int which, 
  boolean isChecked) { 
  Toast.makeText( 
   getBaseContext(), 
   items[which] 
   + (isChecked ? " checked!" 
    : " unchecked!"), 
   Toast.LENGTH_SHORT).show(); 
  } 
  }); 
 return builder.create(); 
 
 } 
 return null; 
 } 
@Override
 protected Dialog onCreateDialog(int id) {
 switch (id) {
 case 0:

 Builder builder = new AlertDialog.Builder(this);
 builder.setIcon(R.drawable.ic_launcher);
 builder.setTitle("This is a dialog with some simple text...");
 builder.setPositiveButton("OK",
  new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog,
  int whichButton) {
  Toast.makeText(getBaseContext(), "OK clicked!",
   Toast.LENGTH_SHORT).show();
  }
  });

 builder.setNegativeButton("Cancel",
  new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog,
  int whichButton) {
  Toast.makeText(getBaseContext(), "Cancel clicked!",
   Toast.LENGTH_SHORT).show();
  }
  });

 builder.setMultiChoiceItems(items, itemsChecked,
  new DialogInterface.OnMultiChoiceClickListener() {
  public void onClick(DialogInterface dialog, int which,
  boolean isChecked) {
  Toast.makeText(
   getBaseContext(),
   items[which]
   + (isChecked ? " checked!"
    : " unchecked!"),
   Toast.LENGTH_SHORT).show();
  }
  });
 return builder.create();

 }
 return null;
 }

然而,Toast类并没有直接用在Activity中,它被用在了AlertDialog类中。所以,这里需要通过getBaseContext()方法获取一个Context类的实例。

2.在Activity中动态地创建一个视图的时候也会遇见Context。

例如,如果想通过硬编码动态地创建一个TextView:

TextView tv = new TextView(this); 
TextView tv = new TextView(this); 

TextView的构造器接受一个Context对象,因为Activity类是Context类的子类,所以可以用this关键字来代替这个Conext对象。

提示:

    使用this动态地创建视图,例如TextView、Button,存在一个潜在的风险——内存泄漏。所以,尽可能地使用getApplicationContext()方法替代this。

这篇关于安卓Android Context类实例详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!