Browse Source

根据屏幕方向,更改布局

liuyuqi-dellpc 4 years ago
parent
commit
0e932bbcad

+ 48 - 16
app/src/main/java/me/yoqi/android/barcode/MainActivity.java

@@ -1,11 +1,15 @@
 package me.yoqi.android.barcode;
 
 import android.Manifest;
+import android.app.Activity;
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.ActivityInfo;
 import android.content.pm.PackageManager;
 import android.graphics.Bitmap;
+import android.graphics.Point;
 import android.os.Bundle;
+import android.view.Display;
 import android.view.View;
 import android.widget.Toast;
 
@@ -37,6 +41,7 @@ public class MainActivity extends AppCompatActivity implements ZxingScanView.OnS
                     ResultMetadataType.SUGGESTED_PRICE,
                     ResultMetadataType.ERROR_CORRECTION_LEVEL,
                     ResultMetadataType.POSSIBLE_COUNTRY);
+
     private ZxingScanView mVScan;
     private ZxingForegroundView mVForeground;
 
@@ -47,7 +52,12 @@ public class MainActivity extends AppCompatActivity implements ZxingScanView.OnS
     @Override
     protected void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        setContentView(R.layout.activity_main);
+        //判断屏幕方向
+        if (screenOrient(this) == 0) {
+            setContentView(R.layout.activity_main__landscape);
+        } else {
+            setContentView(R.layout.activity_main);
+        }
 
         Toolbar toolbar = findViewById(R.id.zsv_toolbar);
         toolbar.setVisibility(View.GONE);
@@ -57,7 +67,6 @@ public class MainActivity extends AppCompatActivity implements ZxingScanView.OnS
         mVScan.addOnScanListener(this);
     }
 
-    // Listener
     @Override
     public void onError(ZxingScanView scanView) {
         switch (scanView.getErrorCode()) {
@@ -67,8 +76,7 @@ public class MainActivity extends AppCompatActivity implements ZxingScanView.OnS
                 break;
             case ZxingScanView.ERROR_CODE_1:
                 // 缺少打开相机的权限
-                if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
-                        Manifest.permission.CAMERA)) {
+                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                     ActivityCompat.requestPermissions(this,
                             new String[]{Manifest.permission.CAMERA},
                             PERMISSIONS_REQUEST_CAMERA);
@@ -77,9 +85,16 @@ public class MainActivity extends AppCompatActivity implements ZxingScanView.OnS
         }
     }
 
+    /**
+     * 扫描结果监听器
+     *
+     * @param scanView    ZxingScanView
+     * @param result      结果 扫描结果
+     * @param barcode     图片 条码图片
+     * @param scaleFactor 缩放比
+     */
     @Override
-    public void onResult(ZxingScanView scanView, Result result, Bitmap barcode,
-                         float scaleFactor) {
+    public void onResult(ZxingScanView scanView, Result result, Bitmap barcode, float scaleFactor) {
         ParsedResult parsedResult = ResultParser.parseResult(result);
         final String format = "format:" + result.getBarcodeFormat().toString();
         final String type = "type:" + parsedResult.getType().toString();
@@ -107,18 +122,35 @@ public class MainActivity extends AppCompatActivity implements ZxingScanView.OnS
     }
 
     @Override
-    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
-                                           @NonNull int[] grantResults) {
+    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
         super.onRequestPermissionsResult(requestCode, permissions, grantResults);
-        switch (requestCode) {
-            case PERMISSIONS_REQUEST_CAMERA: {
-                if (grantResults.length > 0
-                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
-                    mVScan.open();
-                } else {
-                    mVForeground.setMode(ZxingForegroundView.MODE_ERROR);
-                }
+
+        if (requestCode == PERMISSIONS_REQUEST_CAMERA) { //获取照相机权限
+            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
+                mVScan.open(); // 打开摄像头
+            } else {
+                mVForeground.setMode(ZxingForegroundView.MODE_ERROR);
             }
         }
     }
+
+    /**
+     * 判定当前的屏幕是竖屏还是横屏
+     *
+     * @param activity 当前activity对象
+     * @return orient 0横屏,1竖屏
+     */
+    public int screenOrient(Activity activity) {
+        int orient = activity.getRequestedOrientation();
+        //获取屏幕方向,但是如果关闭反转屏幕,则不会反转。但是手机确实翻转了,所以需要手动根据屏幕长宽比判断
+        if (orient != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE && orient != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
+            Display display = activity.getWindowManager().getDefaultDisplay();
+            Point outSize = null;
+            display.getSize(outSize);
+            int screenWidth = outSize.x; //宽
+            int screenHeight = outSize.y; //高
+            orient = screenWidth > screenHeight ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; //宽>高:横屏
+        }
+        return orient;
+    }
 }

+ 6 - 10
app/src/main/res/layout/activity_main.xml

@@ -24,22 +24,18 @@
         app:layout_constraintTop_toBottomOf="@id/zsv_toolbar"
         app:zsvAmbientLight="close"
         app:zsvFeedback="auto"
-        app:zsvScanHeight="400dp"
+        app:zsvScanHeight="200dp"
         app:zsvScanWidth="300dp" />
 
     <TextView
-        android:layout_width="19dp"
-        android:layout_height="206dp"
-        android:layout_marginEnd="20dp"
-        android:layout_marginRight="20dp"
-        android:ems="1"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_marginTop="196dp"
         android:text="@string/alert_title"
         android:textColor="@color/design_default_color_error"
-        android:textSize="20dp"
-        app:layout_constraintBottom_toBottomOf="parent"
         app:layout_constraintEnd_toEndOf="parent"
-        app:layout_constraintTop_toTopOf="parent"
-        app:layout_constraintVertical_bias="0.5" />
+        app:layout_constraintStart_toStartOf="parent"
+        app:layout_constraintTop_toTopOf="parent" />
 
     <me.yoqi.android.zxingscanview.widget.ZxingForegroundView
         android:id="@+id/zsv_zfv_foreground"

+ 59 - 0
app/src/main/res/layout/activity_main__landscape.xml

@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="utf-8"?>
+<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+    <androidx.appcompat.widget.Toolbar
+        android:id="@+id/zsv_toolbar"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        app:layout_constraintEnd_toEndOf="parent"
+        app:layout_constraintStart_toStartOf="parent"
+        app:layout_constraintTop_toTopOf="parent"
+        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
+        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
+        app:title="@string/zsv_label" />
+
+    <me.yoqi.android.zxingscanview.widget.ZxingScanView
+        android:id="@+id/zsv_zsv_scan"
+        android:layout_width="match_parent"
+        android:layout_height="0dp"
+        app:layout_constraintBottom_toBottomOf="parent"
+        app:layout_constraintTop_toBottomOf="@id/zsv_toolbar"
+        app:zsvAmbientLight="close"
+        app:zsvFeedback="auto"
+        app:zsvScanHeight="400dp"
+        app:zsvScanWidth="300dp" />
+
+    <TextView
+        android:layout_width="19dp"
+        android:layout_height="206dp"
+        android:layout_marginEnd="20dp"
+        android:layout_marginRight="20dp"
+        android:ems="1"
+        android:text="@string/alert_title"
+        android:textColor="@color/design_default_color_error"
+        android:textSize="20dp"
+        app:layout_constraintBottom_toBottomOf="parent"
+        app:layout_constraintEnd_toEndOf="parent"
+        app:layout_constraintTop_toTopOf="parent"
+        app:layout_constraintVertical_bias="0.5" />
+
+    <me.yoqi.android.zxingscanview.widget.ZxingForegroundView
+        android:id="@+id/zsv_zfv_foreground"
+        android:layout_width="match_parent"
+        android:layout_height="0dp"
+        app:layout_constraintBottom_toBottomOf="parent"
+        app:layout_constraintTop_toBottomOf="@id/zsv_toolbar"
+        app:layout_constraintVertical_bias="0.0"
+        app:zfvCoverColor="@color/colorRipple"
+        app:zfvErrorDrawable="@drawable/ic_zxingscanview_error"
+        app:zfvResultPointsColor="@color/colorAccent"
+        app:zfvScanFlagDrawable="@drawable/ic_zxing_scan"
+        app:zfvScanRectDrawable="@drawable/ic_zxing_rect"
+        app:zfvZxingScanView="@id/zsv_zsv_scan"
+        tools:layout_editor_absoluteX="-16dp" />
+
+</androidx.constraintlayout.widget.ConstraintLayout>

+ 1 - 0
build.gradle

@@ -1,5 +1,6 @@
 // Top-level build file where you can add configuration options common to all sub-projects/modules.
 apply from: "config.gradle"
+
 buildscript {
     repositories {
         google()

+ 23 - 19
zxingscanview/src/main/java/me/yoqi/android/zxingscanview/widget/ZxingForegroundView.java

@@ -37,7 +37,8 @@ import me.yoqi.android.zxingscanview.R;
 public class ZxingForegroundView extends View {
 
     public static final int MODE_OPEN = 0;
-    public static final int MODE_ERROR = 1;
+    public static final int MODE_ERROR = 1; // 没有摄像头权限错误
+
     private static final long DEFAULT_FRAME_DELAY = 10;//丢失超过30帧就会报警
     private final OnScanListener scanListener = new OnScanListener();
     private final OnStateListener stateListener = new OnStateListener();
@@ -98,8 +99,8 @@ public class ZxingForegroundView extends View {
         int maxNumber = 10;
         int resultPointsColor = 0xc0ffbd21;
         float resultPointsSize = 6;
-        TypedArray custom = getContext().obtainStyledAttributes(attrs,
-                R.styleable.ZxingForegroundView);
+
+        TypedArray custom = getContext().obtainStyledAttributes(attrs, R.styleable.ZxingForegroundView);
         open = custom.getDrawable(R.styleable.ZxingForegroundView_zfvOpenDrawable);
         error = custom.getDrawable(R.styleable.ZxingForegroundView_zfvErrorDrawable);
         scanId = custom.getResourceId(R.styleable.ZxingForegroundView_zfvZxingScanView, scanId);
@@ -107,21 +108,14 @@ public class ZxingForegroundView extends View {
         coverColor = custom.getColor(R.styleable.ZxingForegroundView_zfvCoverColor, coverColor);
         scanRect = custom.getDrawable(R.styleable.ZxingForegroundView_zfvScanRectDrawable);
         scanFlag = custom.getDrawable(R.styleable.ZxingForegroundView_zfvScanFlagDrawable);
-        duration = custom.getInteger(R.styleable.ZxingForegroundView_zfvFlagAnimatorDuration,
-                duration);
-        repeatMode = custom.getInt(R.styleable.ZxingForegroundView_zfvFlagAnimatorRepeatMode,
-                repeatMode);
-        showResultPoints = custom.getBoolean(R.styleable.ZxingForegroundView_zfvShowResultPoints,
-                false);
-        resultPointsAnimatorDuration = custom.getInteger(
-                R.styleable.ZxingForegroundView_zfvResultPointsAnimatorDuration,
-                resultPointsAnimatorDuration);
-        maxNumber = custom.getInteger(R.styleable.ZxingForegroundView_zfvMaxResultPointsNumber,
-                maxNumber);
-        resultPointsColor = custom.getColor(R.styleable.ZxingForegroundView_zfvResultPointsColor,
-                resultPointsColor);
-        resultPointsSize = custom.getDimension(R.styleable.ZxingForegroundView_zfvResultPointsSize,
-                resultPointsSize);
+        duration = custom.getInteger(R.styleable.ZxingForegroundView_zfvFlagAnimatorDuration, duration);
+        repeatMode = custom.getInt(R.styleable.ZxingForegroundView_zfvFlagAnimatorRepeatMode, repeatMode);
+        showResultPoints = custom.getBoolean(R.styleable.ZxingForegroundView_zfvShowResultPoints, false);
+        resultPointsAnimatorDuration = custom.getInteger(R.styleable.ZxingForegroundView_zfvResultPointsAnimatorDuration, resultPointsAnimatorDuration);
+        maxNumber = custom.getInteger(R.styleable.ZxingForegroundView_zfvMaxResultPointsNumber, maxNumber);
+        resultPointsColor = custom.getColor(R.styleable.ZxingForegroundView_zfvResultPointsColor, resultPointsColor);
+        resultPointsSize = custom.getDimension(R.styleable.ZxingForegroundView_zfvResultPointsSize, resultPointsSize);
+
         custom.recycle();
         mScanViewId = scanId;
         setOpenDrawable(open);
@@ -186,6 +180,11 @@ public class ZxingForegroundView extends View {
         drawState(canvas);
     }
 
+    /**
+     * 根据状态重新绘制view
+     *
+     * @param canvas
+     */
     private void drawState(Canvas canvas) {
         if (mScanView == null)
             return;
@@ -222,6 +221,11 @@ public class ZxingForegroundView extends View {
         canvas.restore();
     }
 
+    /**
+     * 绘制错误图标
+     *
+     * @param canvas
+     */
     private void drawError(Canvas canvas) {
         if (mErrorDrawable == null)
             return;
@@ -468,7 +472,7 @@ public class ZxingForegroundView extends View {
         if (mode != MODE_OPEN && mode != MODE_ERROR)
             return;
         this.mode = mode;
-        invalidate();
+        invalidate(); //重新绘制view
     }
 
     /**

+ 7 - 4
zxingscanview/src/main/java/me/yoqi/android/zxingscanview/widget/ZxingScanView.java

@@ -49,11 +49,11 @@ public class ZxingScanView extends SurfaceView {
     private int mScanHeight;
     private int mCameraId;
     private int mErrorCode = ERROR_CODE_NULL;
-    private ArrayList<OnScanListener> mListeners = new ArrayList<>();
-    private ArrayList<OnStateListener> mStateListeners = new ArrayList<>();
+    private final ArrayList<OnScanListener> mListeners = new ArrayList<>();
+    private final ArrayList<OnStateListener> mStateListeners = new ArrayList<>();
     private ScanHandler mScanHandler;
-    private OnResultListener resultListener = new OnResultListener();
-    private ResultPointCallback resultPointCallback = new ResultPointCallback();
+    private final OnResultListener resultListener = new OnResultListener();
+    private final ResultPointCallback resultPointCallback = new ResultPointCallback();
     private int mBarcodeType;
     private String mCharacterSet;
     private Map<DecodeHintType, ?> mBaseHints;
@@ -126,6 +126,9 @@ public class ZxingScanView extends SurfaceView {
         }
     }
 
+    /** 初始化
+     * @param attrs 属性值
+     */
     private void initView(AttributeSet attrs) {
         int mode = AmbientLightManager.MODE_AUTO;
         int feedback = ScanFeedbackManager.MODE_AUTO;

+ 1 - 0
zxingscanview/src/main/res/values/attrs.xml

@@ -1,5 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <resources>
+    <!--    自定义属性-->
     <declare-styleable name="ZxingScanView">
         <attr name="zsvAmbientLight" format="enum">
             <enum name="auto" value="0" />