我正在尝试获取我的窗口的可用(无插图(屏幕宽度和高度。由于API 30不赞成使用过去的方法,我希望使用get bounds部分中讨论的技术:https://developer.android.com/reference/kotlin/android/view/WindowMetrics.为了测试这一点,我在onCreate中调用getWindowManager().getCurrentWindowMetrics()
,并将其分配给一个变量。当我运行它时,我会遇到一个奇怪的运行时错误。如有任何帮助,我们将不胜感激。
崩溃:java.lang.NoSuchMethodError: No interface method getCurrentWindowMetrics()Landroid/view/WindowMetrics; in class Landroid/view/WindowManager; or its super classes (declaration of 'android.view.WindowManager' appears in /system/framework/framework.jar!classes3.dex)
代码:
public class MainView extends AppCompatActivity {
private Context context;
private ProgressBar turnProgressView;
private GameLogicPresenter gameLogicPresenter;
private RelativeLayout boardLayout;
private BoardViewManager boardViewManager;
private ImageView playerGoingImageView;
private int numZoomsSoFar = 0; // Can be positive or negative.
private WindowManager theWindowManager;
private Map<String, Drawable> boardSymbolStringToDrawableMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_in_game_page);
context = MainView.this;
Bundle extras = getIntent().getExtras();
final WindowMetrics metrics = getWindowManager().getCurrentWindowMetrics();
Windowmetrics不能在api低于30、的手机中使用
您尝试使用的API在API 30以下不可用(来源:https://developer.android.com/reference/android/view/WindowMetrics)。看看我为你写的这个代码片段,因为它可能会解决你的问题:
var topInsets = 0
var bottomInsets = 0
var leftInsets = 0
var rightInsets = 0
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
ViewCompat.setOnApplyWindowInsetsListener(requireActivity().window.decorView) { _, windowInsets ->
windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()).let { insets -> // check out WindowInsetsCompat.Type.navigationBars() as well as it might be a better fit for you
topInsets = insets.top
bottomInsets = insets.bottom
leftInsets = insets.left
rightInsets = insets.right
}
windowInsets
}
} else {
requireActivity().windowManager.currentWindowMetrics.windowInsets.getInsets(WindowInsets.Type.systemBars()).let { insets -> // friendly reminder - WindowInsetsCompat.Type.navigationBars()
topInsets = insets.top
bottomInsets = insets.bottom
leftInsets = insets.left
rightInsets = insets.right
}
}