【发布时间】:2019-04-09 12:27:59
【问题描述】:
我想让特定按钮仅在横向模式下显示 - 不显示或纵向可用。我有横向和纵向的单独 xml 文件
我尝试使用 OrientationEventListener,在它运行时,我检查了设备方向是否为横向 - 如果是,我在其上调用了 findViewById,但它由于 NullPointer 而崩溃。到目前为止我的代码:
Button landscapeTest;
public boolean isInLandscape() {
int orientation = getResources().getConfiguration().orientation;
return orientation == Configuration.ORIENTATION_LANDSCAPE;
OrientationEventListener orientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_UI) {
@Override
public void onOrientationChanged(int orientation) {
boolean isInLandscape = isInLandscape();
if (isInLandscape) {
landscapeTest = findViewById(R.id.button_landscape);
landscapeTest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v("landscapeButton", "I am working!!!");
}
});
}
}
};
预期 - 当我更改设备方向(从纵向到横向)时,我应该在 UI 中看到 ID 为 button_landscape 的按钮,当我点击它时,我应该看到“我正在工作!!!”在日志中
实际:当我更改设备方向(从纵向到横向)时,由于找不到按钮,它会与 NullPointer 一起崩溃。
【问题讨论】:
-
将
landscapeTest = findViewById(R.id.button_landscape);放入onCreate。当方向改变时,通过在landscapeTest.setVisibility(View.GONE / View.VISIBLE)之间进行选择来设置可见性 -
最好的做法是,如果你想在不同的模式下显示不同的视图,你可以在 layout-land 文件夹下创建单独的布局文件。
-
您还想将
OnClickListener放在onCreate中,只处理屏幕旋转时的可见性,而不是OnClickListener。 -
在纵向布局中放置相同的按钮,但将它们的可见性设置为
GONE
标签: android button screen-orientation