横竖屏切换

来源:互联网 发布:什么是网络安全意识 编辑:程序博客网 时间:2024/05/29 14:51

相关代码可以在D:\ThreeBao\hengshuping查找

布局切换的按钮

    <ImageView

            android:id="@+id/iv_stretch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:background="@drawable/selector_stretch"----任意一张图片

            android:padding="5dp" />


复制D:\ThreeBao\hengshuping---的DensityUtil.java

在drawable下放图片stretch_focused.png,stretch.png,selector_stretch.xml




//java代码

main{

  
private String path = "http://movie.ks.js.cn/flv/other/1_0.mp4";private Uri uri;private VideoView mVideoView;private ProgressBar pb;private TextView downloadRateView, loadRateView;private int screenWidth;private int screenHeight;private SensorManager sm;private Sensor sensor;private SensorManager sm1;private Sensor sensor1;private OrientationSensorListener2 listener1;private boolean sensor_flag;private boolean stretch_flag;

   
private Handler handler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 888: int orientation = msg.arg1; if (orientation>45&&orientation<135) { }else if (orientation>135&&orientation<225){ }else if (orientation>225&&orientation<315){ System.out.println("切换成横屏"); VideoViewBuffer.this.setRequestedOrientation(0); sensor_flag = false; stretch_flag =false; }else if ((orientation>315&&orientation<360)||(orientation>0&&orientation<45)){ System.out.println("切换成竖屏"); VideoViewBuffer.this.setRequestedOrientation(1); sensor_flag = true; stretch_flag =true; } break; default: break; } };};
private OrientationSensorListener listener;private View sf_play;private ImageView iv_stretch;

oncreate{

requestWindowFeature(Window.FEATURE_NO_TITLE);WindowManager windowManager = getWindowManager();Display display = windowManager.getDefaultDisplay();screenWidth = display.getWidth();screenHeight = display.getHeight();setContentView(R.layout.videobuffer);initView();//注册重力感应器  屏幕旋转sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE);sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);listener = new OrientationSensorListener(handler);sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);//根据  旋转之后 点击 符合之后 激活smsm1 = (SensorManager)getSystemService(Context.SENSOR_SERVICE);sensor1 = sm1.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);listener1 = new OrientationSensorListener2();sm1.registerListener(listener1, sensor1, SensorManager.SENSOR_DELAY_UI);} 


@Override
    protected void onResume() {
        //sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);
        super.onResume();
    }
    
    @SuppressLint("NewApi")
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        
        System.out.println("screenHeight  "+screenHeight);
        System.out.println("screenWidth  "+screenWidth);
        if (stretch_flag) {
            //切换成竖屏
            LayoutParams params1 = new RelativeLayout.LayoutParams(screenHeight,DensityUtil.dip2px(this, 160));
            sf_play.setLayoutParams(params1);
            Toast.makeText(getApplicationContext(), "竖屏", 0).show();
            
        }
        else {
            //切换成横屏
            LayoutParams params1 = new RelativeLayout.LayoutParams(screenHeight,screenWidth);
            
            sf_play.setLayoutParams(params1);
            
            Toast.makeText(getApplicationContext(), "横屏", 0).show();
            
        }    
    }
    
    private void initView() {
        sf_play = (VideoView1) findViewById(R.id.sf_play);
        
        ll_playcontroller=(LinearLayout)findViewById(R.id.ll_playcontroller);
        ll_playcontroller.getBackground().setAlpha(150);
        
        iv_stretch = (ImageView) findViewById(R.id.iv_stretch);
        iv_recordcourse_start = (ImageView) findViewById(R.id.iv_recordcourse_start);
        iv_stretch.setOnClickListener(this);
        iv_recordcourse_start.setOnClickListener(this);
        
    }


    @Override
    public void onClick(View arg0) {
        switch(arg0.getId()){
            
        case R.id.iv_stretch:
            sm.unregisterListener(listener);
            Toast.makeText(getApplicationContext(), "点击切换屏幕", 0).show();
            if (stretch_flag) {
                stretch_flag = false;
                //切换成横屏
                MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                
            }else{
                stretch_flag = true;
                //切换成竖屏
                MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                
            }
        break;
        }
    }

    
    /**
     * 重力感应监听者
     */
    public class OrientationSensorListener implements SensorEventListener {
         private static final int _DATA_X = 0;
         private static final int _DATA_Y = 1;
         private static final int _DATA_Z = 2;
         
         public static final int ORIENTATION_UNKNOWN = -1;
         
         private Handler rotateHandler;
         
         public OrientationSensorListener(Handler handler) {
             rotateHandler = handler;
         }

        public void onAccuracyChanged(Sensor arg0, int arg1) {
            // TODO Auto-generated method stub

        }

        public void onSensorChanged(SensorEvent event) {
            
            if(sensor_flag!=stretch_flag)  //只有两个不相同才开始监听行为
            {
            float[] values = event.values;
            int orientation = ORIENTATION_UNKNOWN;
            float X = -values[_DATA_X];
            float Y = -values[_DATA_Y];
            float Z = -values[_DATA_Z];        
            float magnitude = X*X + Y*Y;
            // Don't trust the angle if the magnitude is small compared to the y value
            if (magnitude * 4 >= Z*Z) {
                //屏幕旋转时
                float OneEightyOverPi = 57.29577957855f;
                float angle = (float)Math.atan2(-Y, X) * OneEightyOverPi;
                orientation = 90 - (int)Math.round(angle);
                // normalize to 0 - 359 range
                while (orientation >= 360) {
                    orientation -= 360;
                }
                while (orientation < 0) {
                    orientation += 360;
                }
            }
            if (rotateHandler!=null) {
                rotateHandler.obtainMessage(888, orientation, 0).sendToTarget();
            }
            
            }
        }
    }
    
    
    public class OrientationSensorListener2 implements SensorEventListener {
            private static final int _DATA_X = 0;
            private static final int _DATA_Y = 1;
            private static final int _DATA_Z = 2;
            
            public static final int ORIENTATION_UNKNOWN = -1;
            
            public void onAccuracyChanged(Sensor arg0, int arg1) {
                // TODO Auto-generated method stub
                
            }
            
            public void onSensorChanged(SensorEvent event) {
            
                float[] values = event.values;
                
                int orientation = ORIENTATION_UNKNOWN;
                float X = -values[_DATA_X];
                float Y = -values[_DATA_Y];
                float Z = -values[_DATA_Z];        
                
                /**
                 * 这一段据说是 android源码里面拿出来的计算 屏幕旋转的 不懂 先留着 万一以后懂了呢
                 */
                float magnitude = X*X + Y*Y;
                // Don't trust the angle if the magnitude is small compared to the y value
                if (magnitude * 4 >= Z*Z) {
                    //屏幕旋转时
                    float OneEightyOverPi = 57.29577957855f;
                    float angle = (float)Math.atan2(-Y, X) * OneEightyOverPi;
                    orientation = 90 - (int)Math.round(angle);
                    // normalize to 0 - 359 range
                    while (orientation >= 360) {
                        orientation -= 360;
                    }
                    while (orientation < 0) {
                        orientation += 360;
                    }
                }
                
                 if (orientation>225&&orientation<315){  //横屏
                        sensor_flag = false;
                    }else if ((orientation>315&&orientation<360)||(orientation>0&&orientation<45)){  //竖屏
                        sensor_flag = true;
                    }
                
                 if(stretch_flag== sensor_flag){  //点击变成横屏  屏幕 也转横屏 激活
                     System.out.println("激活");
                     sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);
                    
                 }
        }
     }

}












DensityUtil.java-创建

package com.daemon.viewlp;
import java.lang.reflect.Field;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.WindowManager;

public class DensityUtil {

    /**
     * 根据手机的分辨率�?dp 的单�?转成�?px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率�?px(像素) 的单�?转成�?dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    
    
    
    public static DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        return dm;
    }
    
    /**
     * 获取状�?栏高�?
     *
     * @param context
     * @return
     */
    public static int getStatuBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, sbar = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sbar = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            // e1.printStackTrace();
        }
        return sbar;
    }
}

0 0
原创粉丝点击