1. 程式人生 > >Accessing Outside Variables with the Final Keyword內部類訪問外部變數

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型別的!!!