安卓Android Context类实例详解
程序员文章站
2024-03-05 11:40:36
1.例如下面的代码片段,toast类的第一个参数接受一个context对象:
@override
protected dialog oncreatedi...
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。