当调用onConfigurationChanged
时,视图在屏幕上的位置尚未更新。您需要向视图添加一个OnLayoutChangeListener
来捕获您要查找的更新。请参见下面的示例。
TestDialogFragment.java
public class TestDialogFragment extends DialogFragment {
private static final String TAG = "TestDialogFragment";
View testView;
int[] testViewLocation = {0, 0};
public TestDialogFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test_fragment, container);
testView = view.findViewById(R.id.test_view);
testView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
Log.d(TAG, "onLayoutChange");
testView.getLocationOnScreen(testViewLocation);
Log.d(TAG, String.format("%s %s", testViewLocation[0], testViewLocation[1]));
}
});
return view;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, "onConfigurationChanged");
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Log.d(TAG, "landscape");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Log.d(TAG, "portrait");
}
testView.getLocationOnScreen(testViewLocation);
Log.d(TAG, String.format("%s %s", testViewLocation[0], testViewLocation[1]));
}
}
test_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@+id/test_view"
android:layout_height="50dp"
android:layout_width="match_parent"
android:layout_gravity="center"/>
</FrameLayout>
日志输出
06-24 16:20:05.682 D/TestDialogFragment﹕ onConfigurationChanged
06-24 16:20:05.682 D/TestDialogFragment﹕ portrait
06-24 16:20:05.682 D/TestDialogFragment﹕ 504 601
06-24 16:20:05.852 D/TestDialogFragment﹕ onLayoutChange
06-24 16:20:05.852 D/TestDialogFragment﹕ 84 1021
06-24 16:20:08.695 D/TestDialogFragment﹕ onConfigurationChanged
06-24 16:20:08.695 D/TestDialogFragment﹕ landscape
06-24 16:20:08.695 D/TestDialogFragment﹕ 84 1021
06-24 16:20:08.865 D/TestDialogFragment﹕ onLayoutChange
06-24 16:20:08.865 D/TestDialogFragment﹕ 504 601
06-24 16:20:13.550 D/TestDialogFragment﹕ onConfigurationChanged
06-24 16:20:13.550 D/TestDialogFragment﹕ portrait
06-24 16:20:13.550 D/TestDialogFragment﹕ 504 601
getLocationOnScreen
相关的代码。这个 不完全是你的问题,但我想知道它是否有类似的原因。 - mpkuthandroid:configChanges
上,它禁用了活动的重新创建。在这种情况下,由于活动没有被销毁,对话框也没有被销毁。这就是为什么视图的位置仍然是旧的。不需要代码,因为这很容易重现。 - Pedro Oliveira