Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 安卓Android Context類實例詳解

安卓Android Context類實例詳解

編輯:關於Android編程

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。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved