Accessing Outside Variables with the Final Keyword内部类访问外部变量

Sometimes you want to access information available outside of the inner class. Consider the following example. You’ve got a screen with two controls: a Button and a TextView. Each time the user clicks on the Button control, the TextView control is updated with the current time. Within the Activity class associated with this layout, youcould implement this functionality as follows:

Button myButton = (Button) findViewById(R.id.ButtonToClick);
myButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        SimpleDateFormat formatter = new SimpleDateFormat("h:mm:ss a");
        String strWhen = formatter.format(new Date());
        TextView myTextview = (TextView)
            findViewById(R.id.TextViewToShow);
        myTextview.setText("Clicked at " +  strWhen);
    }
});

The above code will run and behave as expected. However, let’s say you really wanted to declare the TextView control outside the inner class and use it for other purposes as well. Perhaps you’d try to do this instead:

TextView myTextview = (TextView) findViewById(R.id.TextViewToShow);
Button myButton = (Button) findViewById(R.id.ButtonToClick);
myButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        SimpleDateFormat formatter = new SimpleDateFormat("h:mm:ss a");
        String strWhen = formatter.format(new Date());
        myTextview.setText("Clicked at " +  strWhen);
    }
});

Unfortunately, this won’t compile. Instead, you’ll get the compile error “Cannot refer to a non-final variable myTextview inside an inner class defined in a different method”. As the error suggests, what you need to do is make the TextView variable final, so that it is accessible within the inner class’s onClick() method:

final TextView myTextview = (TextView) findViewById(R.id.TextViewToShow);
Button myButton = (Button) findViewById(R.id.ButtonToClick);
myButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        SimpleDateFormat formatter = new SimpleDateFormat("h:mm:ss a");
        String strWhen = formatter.format(new Date());
        myTextview.setText("Clicked at " +  strWhen);
    }
});

This code will indeed compile and run as expected.

就是说内部内要访问外部的变量,只能访问final类型的!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值