如何从OrientationEventListener返回布尔类型?

时间:2017-10-30 16:15:11

标签: android orientation

我在Android Studio中遇到了一个问题,但我很新。我必须创建一个在调用onResume()方法时始终递增的变量,但如果方向已更改,则变量不得递增。

我想在onResume()方法中使用if-else语句来解决这个问题(如果OrientationEventListener返回false,则会增加变量;如果方向发生变化,则不会影响变量(true) )),并用toasts写出变量的值。但是,我不知道如何从中获取布尔类型返回,即使我搜索了几个小时的答案。 有类似的问题,但我无法成功地实现他们的灵魂。如果有帮助,这是我的代码:

public class MainActivity extends Activity {
    public static final String MY_TAG = "tagged";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void mOrientationListener = new OrientationEventListener(this SensorManager.SENSOR_DELAY_NORMAL) {
        @Override
        public void onOrientationChanged(int orientation) {

        }
    };

    public void onResume() {
        super.onResume();
        setContentView(R.layout.activity_main);
        int sum = 0;
        int ak = int onOrientationChanged;
        if ( != 0) {
            Log.i(MY_TAG, "onResume");
            tToast("onResume:");
            sum++;
            nToast(sum);
        }else {
            nToast(sum);
        }
    }
    private void tToast(String s) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, s, duration);
        toast.show();
    }
    private void nToast(Integer a) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, a, duration);
        toast.show();
    }
}

1 个答案:

答案 0 :(得分:1)

当您需要知道设备旋转的精确方向(从0到359)时,使用

OrientationEventListener。我假设你在谈论风景/肖像意义上的方向,所以OrientationEventListener并不是解决这个问题的正确方法。

我认为最好的办法是每次检查onCreate()中的方向,并将其与之前的方向进行比较,以设置标记didChangeOrientation或类似的东西,然后你可以在onResume()操作中使用此标记。

private int orientation;
private boolean didChangeOrientation;

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("orientation", orientation);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    orientation = getResources().getConfiguration().orientation;        

    if (savedInstanceState != null) {
        int previousOrientation = savedInstanceState.getInt("orientation");
        didChangeOrientation = (orientation != previousOrientation);
    }
    else {
        didChangeOrientation = false;
    }

    ...
}

@Override
public void onResume() {
    super.onResume();

    if (!didChangeOrientation) {
        // your code here
    }
}