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

问题描述 投票:-5回答:3

我希望特定按钮仅在横向模式下显示 - 不显示或以纵向显示。我有横向和纵向的单独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的按钮,当我点击它时,我应该看到“我正在工作!!!”在logcat中

实际:当我更改设备方向(从纵向到横向)时,它会与NullPointer崩溃,因为它无法找到按钮。

android button screen-orientation
3个回答
0
投票

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

请阅读Handle Runtime Changes

1)如果你想在不同模式下显示不同的布局,我建议创建具有相同名称的纵向模式(layout / layout.xml)和横向模式(layout-land / layout.xml)的单独文件。因此android将处理方向更改。

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


0
投票

就像我在评论部分提到的那样。您只想在方向发生变化时处理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);
        }
    }

}

0
投票

试试这会帮助你:

@Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            landscapeTest.setVisibility(View.VISIBLE);
        } else {
            landscapeTest.setVisibility(View.GONE);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.