专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Android

请教把Dialog声明为final有什么好处

发布时间:2010-05-30 10:56:32 文章来源:www.iduyao.cn 采编人员:星星草
请问把Dialog声明为final有什么好处?
Java code

public class AlertDialogStudy extends Activity {
14        /** Called when the activity is first created. */
15        @Override
16        public void onCreate(Bundle savedInstanceState) {
17            super.onCreate(savedInstanceState);
18            setContentView(R.layout.main);
19     
20            // get button
21            Button btnShow = (Button)findViewById(R.id.btn_show);
22            btnShow.setOnClickListener(new View.OnClickListener() {
23     
24                @Override
25                public void onClick(View v) {
26                    AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
27                    builder.setTitle("Auto-closing Dialog");
28                    builder.setMessage("After 2 second, this dialog will be closed automatically!");
29                    builder.setCancelable(true);
30     
31                    final AlertDialog dlg = builder.create();
32     
33                    dlg.show();
34     
35                    final Timer t = new Timer();
36                    t.schedule(new TimerTask() {
37                        public void run() {
38                            dlg.dismiss(); // when the task active then close the dialog
39                            t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
40                        }
41                    }, 2000); // after 2 second (or 2000 miliseconds), the task will be active.
42     
43                }
44            });
45        }
46    }


这段代码中的dialog被声明为final,请问这样做有什么好处呢?

------解决方案--------------------
使用final方法的原因有二:
  第一、把方法锁定,防止任何继承类修改它的意义和实现。
  第二、高效。编译器在遇到调用final方法时候会转入内嵌机制,大大提高执行效率。

在这里使用final,应该只是单纯的让run方法里面可以调用到Dialog对象。
------解决方案--------------------
楼下回答是靠谱。

这是java处理闭包的功能。

如果按照楼主的代码将 final 去掉,那么在run方法中就无法访问t对象,典型闭包问题。
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: