[英]Variable is accessed from within inner class inside another inner class
我在另一個內部 class 中有一個內部 class,我試圖在兩個內部類之外使用最終變量。 這是代碼:
final View v = inflater.inflate(R.layout.fragment_floor_plan, container, false); //final variable
final Button button0 = v.findViewById(R.id.button21);
button0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final PhotoView photoView = v.findViewById(R.id.photo_view); //works fine here
photoView.setAlpha(0f);
System.out.println(photoView.isZoomable());
System.out.println(photoView.VISIBLE);
photoView1.animate().alpha(0f).setDuration(250);
photoView.animate().alpha(1f).setDuration(250);
photoView.bringToFront();
photoView.setOnScaleChangeListener(new OnScaleChangedListener() {
@Override
public void onScaleChange(float scaleFactor, float focusX, float focusY) {
if (photoView.getScale() <= photoView.getMinimumScale() + 0.1f) {
LinearLayout linearLayout = v.findViewById(R.id.linearLayout); //doesn't work here
linearLayout.bringToFront();
}
}
}
}
});
如何讓它在 OnScaleChangedListener 中工作?
現在我看了一下,您的問題可能是 View v 正在作為參數傳遞給 OnClickListener 的 onClick 方法,並且下面的代碼可能試圖訪問而不是您的頂級 View 變量。
我的建議是重構您的變量名稱,以便您引用正確的變量。 如果傳入的 View 是您真正想要使用的,則應在方法簽名中將其聲明為 final:
public void onClick(final View v) {
如果嵌套匿名 class 的封閉 scope 中的變量被聲明為最終或有效最終,則您應該能夠從任何級別的嵌套內部匿名類中訪問它。
為了確保這一點,我做了一個小例子並自己嘗試了一下:
import java.util.function.*;
public class Main {
public static void main(String[] args) {
final int test = 11;
Runnable runnable = new Runnable() {
public void run() {
Runnable runnable = new Runnable() {
public void run() {
System.out.println(test);
}
};
runnable.run();
}
};
runnable.run();
}
}
如您所見,第二個可運行對象嵌套在另一個可運行對象中,運行代碼會訪問 integer 測試並按應有的方式打印它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.