简体   繁体   English

加速度计android倾斜功能

[英]Accelerometer android tiltfunction

Im testing out the accelerometer, and trying to make a program that show a text depending on where the user tilts the phone.我测试了加速度计,并尝试制作一个程序,根据用户倾斜手机的位置显示文本。 I have a text that will show when the user tilts the phone right/left and up/down.我有一个文本,当用户向右/向左和向上/向下倾斜手机时会显示。

I am new to android so if you think this question is stupid, please dont vote down!我是 android 新手,所以如果您认为这个问题很愚蠢,请不要投反对票! Tell my what i did wrong with the question so i can do beter next time!告诉我我在这个问题上做错了什么,这样我下次可以做得更好!

The code below dosent work well, i only get right and top.. and i cant figure out why..下面的代码工作得很好,我只得到正确和顶部..我不知道为什么..

The code for doing this:执行此操作的代码:

@Override
    public void onSensorChanged(SensorEvent event) {
        // get the change of the x,y,z values of the accelerometer
        deltaX = Math.abs(lastX - event.values[0]);
        deltaY = Math.abs(lastY - event.values[1]);
        deltaZ = Math.abs(lastZ - event.values[2]);

        if (deltaX > 2){
            HideText();
            findViewById(R.id.txtRight).setVisibility(View.VISIBLE);
        }
        if (deltaY > 2)
        {
            HideText();
            findViewById(R.id.txtUp).setVisibility(View.VISIBLE);
        }
        if (deltaX < -2)
        {
            HideText();
            findViewById(R.id.txtLeft).setVisibility(View.VISIBLE);
        }
        if (deltaY < -2) {
            HideText();
            findViewById(R.id.txtUp).setVisibility(View.VISIBLE);
        }

        /*else if ((deltaX > vibrateThreshold) || (deltaY > vibrateThreshold) || (deltaZ > vibrateThreshold)){
            v.vibrate(100);
            HideText();
            Toast.makeText(getApplicationContext(), "Stop shaking me!!!",
                    Toast.LENGTH_LONG).show();
        }*/


    }

The code that is comment out i tried to use if the user shakes the phone.. but will save that for later :)如果用户摇晃手机,我尝试使用的注释掉的代码..但会保存以备后用:)

The code looks fine.代码看起来不错。 Your problem comes from Math.abs() - it takes the absolute value of the difference which means it always makes it positive and deltaX and deltaY will never be <0.您的问题来自Math.abs() - 它取差值的绝对值,这意味着它始终为正值,并且deltaXdeltaY永远不会<0。 Remove Math.abs() and it should be OK.删除Math.abs()应该没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM