无法从内部类中访问全局final变量

时间:2015-10-12 01:07:59

标签: android

我正在使用动画将视图滑动到屏幕顶部。动画的代码包含在一个名为LoopAnimation()的方法中,该方法从main调用。

public class MainActivity extends AppCompatActivity {

final View view = findViewById(R.id.view);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LoopAnimation(view); \\ The animation loop method

}

LoopAnimation()方法使用嵌套的setOnClickListener来创建动画循环

public void LoopAnimation(View view){
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // starts the animation
            view.animate().translationY(-100);
            view.animate().setDuration(1500);

            // reverses the animation
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Do some job here
                    view.animate().translationY(100);
                    view.animate().setDuration(1500);

                    LoopAnimation(view); // Method calls itself 
                                         // to create loop effect

                }
            });

        }
    });
}

问题在于我得到了一个我无法理解的微不足道的错误。虽然我已将view声明为全局和最终版,但我在LoopAnimation()

中收到此错误
Variable 'view' is accessed from within inner class, needs to be declared final. 

1 个答案:

答案 0 :(得分:3)

您正在使用在方法范围内定义的变量view。请注意,您的方法的参数也称为view,因此您实际上并未使用您认为正在使用的全局变量。

public void LoopAnimation(View view){

编辑:我更多地考虑了您尝试这样做的方式,而这种做法并不是我想做的。这是更合理的事情:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        View view = findViewById(R.id.view);
        view.setOnClickListener(new View.OnClickListener() {

            private boolean _forwards = true;

            @Override
            public void onClick(View v) {
                if (_forwards) {
                    // starts the animation
                    v.animate().translationY(-100);
                    v.animate().setDuration(1500);
                    _forwards = false;
                } else {
                    // reverses the animation
                    v.animate().translationY(100);
                    v.animate().setDuration(1500);
                    _forwards = true;
                }
            }
        }
    }
}
相关问题