让某些按钮仅在横向模式下显示



我想让特定按钮仅在横向模式下显示 - 不以纵向显示或可用。我有单独的横向和纵向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的按钮,当我点击它时,我应该在日志中看到"我正在工作!!">

实际:当我更改设备方向(从纵向到横向(时,它会因找不到按钮而崩溃。

崩溃背后的原因是当您更改方向时,Android 会重新启动活动。并再次打电话给OnCreate()

请阅读处理运行时更改

1(如果您想在不同的模式下显示不同的布局,我建议为纵向模式(布局/布局.xml(和横向模式(布局-土地/布局.xml(创建具有相同名称的单独文件。所以安卓将处理方向的变化。

2(如果您不想创建两个单独的布局文件并从类文件中处理它。请将您的代码移动到OnCreate(),并从OnCreate()检查布局是纵向还是横向。因为onClickListener不属于onOrientationChanged.它还将解决NullPointerException问题。根据方向,您可以隐藏/显示按钮。

就像我在评论部分提到的。您只想在方向更改时处理Button的可见性。

landscapeTest = findViewById(R.id.button_landscape);

应该在OnCreate和你的OnClickListener.

下面是一个示例:

public class SomeActivity extends Activity {    
Button landscapeTest;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_some);
    landscapeTest = findViewById(R.id.button_landscape);
    landscapeTest.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           Log.v("landscapeButton", "I am working!!!");
       }
    });
    OrientationEventListener orientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_UI) {
    @Override
    public void onOrientationChanged(int orientation) {
        boolean isInLandscape = isInLandscape();
        if (isInLandscape) {
        landscapeTest.setVisibility(View.GONE);
        }else{
        landscapeTest.setVisibility(View.VISIBLE);
        }
    }
}

试试这个将帮助您:

@Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            landscapeTest.setVisibility(View.VISIBLE);
        } else {
            landscapeTest.setVisibility(View.GONE);
        }
    }

最新更新