作者qrtt1 (有些事,有時候。。。)
看板java
標題Re: [問題] this
時間Wed Jul 23 16:54:15 2014
※ 引述《gn00618777 (非常念舊)》之銘言:
: 在寫Activity的程式碼中
: TextView lb101=new TextView (this)
: 書上解釋說參數是Contex物件,可以用this取得...
: 我以前學生時期的理解是 this 是你現在呼叫的物件本身,也就是lb101
[---------]
不是呦,是你那一個 Activity 本身
(我假設你在寫 onCreate )
public class MyApp extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
TextView lb101=new TextView (this);
// ..........................................
}
}
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
Within an instance method or a constructor,
this is a reference to the current object — the object whose method
or constructor is being called.
You can refer to any member of the current object
from within an instance method or a constructor by using this.
: 他說啥contex物件?不太懂
: TextView這建構子參數為何還要丟自己建立的物件?
: 謝謝。
因為它的繼承關係是長成這個樣子!
http://developer.android.com/reference/android/app/Activity.html
java.lang.Object
android.content.Context
android.content.ContextWrapper
android.view.ContextThemeWrapper
android.app.Activity
所以 Activity 物件,也能視為 Context 物件。
有不懂時,先翻翻 javadoc 找找線索嚕,挺有幫助的。
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.231.151.73
※ 文章網址: http://www.ptt.cc/bbs/java/M.1406105657.A.94D.html
※ 編輯: qrtt1 (36.231.151.73), 07/23/2014 16:57:49
推 LPH66:這就是繼承的"IS-A"(「是一個」)關係 07/23 16:56
→ qrtt1:class BadQrtt1 extends Qrtt1 {} 07/23 16:58
→ qrtt1:壞掉的 qrtt1 是一個 qrtt1 (只是他壞掉了...xd) 07/23 16:58
※ 編輯: qrtt1 (36.231.151.73), 07/23/2014 17:00:36
推 gn00618777:我大概懂了,TextView這類別,需要用到Activity物件的 07/23 17:32
→ gn00618777:某成員或某成員方法,只是..為啥會用到?有簡單的例子嗎 07/23 17:32