- 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对象,典型闭包问题。