2013-11-23 3 views
5

Я пытаюсь создать макет, который содержит «SurfaceView» наверху, с горизонтальной панелью инструментов, которая разделена на 3 сегмента внизу, однако мой SurfaceView, который содержит предварительный просмотр камеры, является только отображается только один элемент. Пожалуйста, укажите ошибку в моем макете xml или предоставите мне аналогичный макет xml, Спасибо.Помощник макета Android, отсутствующие элементы

Ниже мое расположение & обновления на основе рекомендаций пользователей

Попытка # 1 (RelativeLayout как корень):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/LayoutForPreview" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    android:screenOrientation="portrait" > 

    <SurfaceView 
     android:id="@+id/surfaceViewBarcodeScanner" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_above="@+id/linearLayoutToolbar" 
     android:layout_gravity="top" 
     android:scaleType="fitXY" /> 

    <LinearLayout 
     android:id="@+id/linearLayoutToolbar" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:orientation="horizontal" > 

     <ImageView 
      android:id="@+id/imageView1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:scaleType="fitXY" 
      android:src="@drawable/scanner_bottom_left" /> 

     <ImageView 
      android:id="@+id/imageView2" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_weight="0.68" 
      android:scaleType="fitXY" 
      android:src="@drawable/scanner_bottom_center_toolbar" /> 

     <ImageView 
      android:id="@+id/imageView3" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:scaleType="fitXY" 
      android:src="@drawable/scanner_bottom_right_landscape_button" /> 
    </LinearLayout> 

</RelativeLayout> 

Ниже мой желаемый вид GUI:

enter image description here

Попытка # 1 Результат, устройство снимок, который показывает только SurfaceView:

enter image description here

Снимок затмение GUI инструмент, который показывает, что макет должен выглядеть. enter image description here

Попытка # 2 (LinearLayout как корень):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/LayoutForPreview" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    android:screenOrientation="portrait" > 

    <SurfaceView 
     android:id="@+id/surfaceViewBarcodeScanner" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="top" 
     android:scaleType="fitXY" 
     android:layout_weight="1" /> 

    <LinearLayout 
     android:id="@+id/linearLayoutToolbar" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" 
     android:layout_gravity="bottom" > 

     <ImageView 
      android:id="@+id/imageView1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:scaleType="fitXY" 
      android:src="@drawable/scanner_bottom_left" /> 

     <ImageView 
      android:id="@+id/imageView2" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_weight="0.68" 
      android:scaleType="fitXY" 
      android:src="@drawable/scanner_bottom_center_toolbar" /> 

     <ImageView 
      android:id="@+id/imageView3" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:scaleType="fitXY" 
      android:src="@drawable/scanner_bottom_right_landscape_button" /> 
    </LinearLayout> 

</LinearLayout> 

Попытка # 2, Результат, устройство снимок:

enter image description here

Вопросы:

появляется

1) Панель инструментов на вершине, а не на нижней

2) предварительного просмотра камеры замерзает & приложение падает. По какой-то причине LinearLayout вызывает ошибку камеры 1001, и я думаю, что она связана с размерами предварительного просмотра.

Попытка № 3 (Добавить программную панель в программную сторону либо в относительную, либо в линейную компоновку в операции onCreate).

LinearLayout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/LayoutForPreview" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    android:screenOrientation="portrait" > 

    <SurfaceView 
     android:id="@+id/surfaceViewBarcodeScanner" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="top" 
     android:scaleType="fitXY" 
     android:layout_weight="1" /> 

</LinearLayout> 

Панель инструментов определены в отдельном XML добавлены позже с помощью Java-код:

<?xml version="1.0" encoding="UTF-8"?> 
<!-- LinearLayout that contains toolbar that is divided into 3 sections horizontally , layout_below="@+id/BarcodeScannerFrame--> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/linearLayoutToolbar" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_gravity="bottom" 
    android:orientation="horizontal" > 

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:scaleType="fitXY" 
     android:src="@drawable/scanner_bottom_left" /> 

    <ImageView 
     android:id="@+id/imageView2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="0.68" 
     android:scaleType="fitXY" 
     android:src="@drawable/scanner_bottom_center_toolbar" /> 

    <ImageView 
     android:id="@+id/imageView3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:scaleType="fitXY" 
     android:src="@drawable/scanner_bottom_right_landscape_button" /> 
</LinearLayout> 

OnCreate, onResume, другие соответствующие фрагменты кода только моей деятельности, панель LinearLayout добавляется к линейной или относительной компоновке во время выполнения:

//import not included 
    public class ScanVinFromBarcodeActivity extends Activity { 
     // camera object that is used globally in this activity and also passed 
     // reference to PreviewSurface inner class 
     private Camera globalCamera; 
     private int cameraId = 0; 
     // bitmap that would created after picture is taken and converted from 
     // camera bytes 
     private Bitmap bmpOfTheImageFromCamera = null; 
     // global flag whether a camera has been detected 
     private boolean isThereACamera = false; 
     // layout for this activity 
     private LinearLayout RelativeLayoutBarcodeScanner= null; 
     // CameraPreview extends SurfaceView displays preview of images from the 
     // Camera 
     private CameraPreview newCameraPreview = null; 
     // used to inflate the xml layout 
     private SurfaceView surfaceViewBarcodeScanner = null; 
     private boolean cameraPreviewing = false; 
     // this continueToAutomaticallyDecode flag is initially set to TRUE, but 
     // will be set to FALSE on the first successful decode OR when a crucial 
     // method in the code process fails or throws an exception 
     private volatile boolean continueToAutomaticallyDecode = true; 
     // global flag used to indicate picture taking & decoding is in progress 
     private volatile boolean takingPictureAndDecodeInprogress = false; 
     // Bitmap options for bitmap creation from camera picture 
     BitmapFactory.Options options = null; 
     // used for samsung galaxy s devices only 
     private Matrix rotationMatrix90CounterClockWise = null; 
     // Reader is class from zxing used to decode barcodes 
     Reader reader = null; 
     // DecodeHintType hashtable is used to provide help to the zxing Reader 
     // class 
     Hashtable<DecodeHintType, Object> decodeHints = null; 
     // 
     private boolean onTouchEvent = true; 
     // 
     private OrientationEventListener orientationEventListener = null; 
     // 1 means the screen is PORTRAIT and 2 means screen is LANDSCAPE 
     private int latestScreenOrientation = 1; 
     // 
     Camera.Parameters Flash = null; 
     // 
     private String globalVIN = null; 
     // 
     private Handler handler = null; 
     // 
     private LinearLayout barcodeVinScannerToolbar = null; 

     public boolean isContinueToAutomaticallyDecode() { 

      return continueToAutomaticallyDecode; 
     } 

     public void setContinueToAutomaticallyDecode(
       boolean continueToAutomaticallyDecode) { 

       this.continueToAutomaticallyDecode = continueToAutomaticallyDecode; 

     } 

     public boolean isTakingPictureAndDecodeInprogress() { 
      return takingPictureAndDecodeInprogress; 
     } 

     public void setTakingPictureAndDecodeInprogress(
       boolean takingPictureAndDecodeInprogress) { 

       this.takingPictureAndDecodeInprogress = takingPictureAndDecodeInprogress; 

     } 

     /* 
     * This method , finds FEATURE_CAMERA, opens the camera, set parameters , 
     * add CameraPreview to layout, set camera surface holder, start preview 
     */ 
     @SuppressLint("InlinedApi") 
     private void initializeGlobalCamera() { 

      try { 
       if (!getPackageManager().hasSystemFeature(
         PackageManager.FEATURE_CAMERA)) { 
        Toast.makeText(this, "No camera on this device", 
          Toast.LENGTH_LONG).show(); 
       } else { // check for front camera ,and get the ID 
        cameraId = findFrontFacingCamera(); 
        if (cameraId < 0) { 

         Toast.makeText(this, "No front facing camera found.", 
           Toast.LENGTH_LONG).show(); 
        } else { 

         Log.d("ClassScanViewBarcodeActivity", 
           "camera was found , ID: " + cameraId); 
         // camera was found , set global camera flag to true 
         isThereACamera = true; 
         // OPEN 
         globalCamera = getGlobalCamera(cameraId); 
         // parameters auto focus 
         globalCamera.getParameters().setFocusMode(
           Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); 
         // set picture format to JPEG, everytime makesure JPEg 
         globalCamera.getParameters().setPictureFormat(
           ImageFormat.JPEG); 
         autoFocusSetupForBarcode(globalCamera); 
         /* 
         * START early setup variables & setting used in 
         * jpegCallback in order to optimize the jpegCallback code 
         */ 
         options = new BitmapFactory.Options(); 
         // option set for down sampling he captured image taken from 
         // the camera in order to MemoryOutOfBounds exception 
         options.inSampleSize = 4; 
         // image quality rather than speed in order to achieve early 
         // barcode detection & decode 
         options.inPreferQualityOverSpeed = false; 
         // Samsung galaxy S only , rotate to correct orientation 
         // ,and capture only the image within the guidance rectangle 

         rotationMatrix90CounterClockWise = new Matrix(); 
         rotationMatrix90CounterClockWise.postRotate(90); 
         // early variable used by zxing to decode method 
         decodeHints = new Hashtable<DecodeHintType, Object>(); 
         decodeHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); 
         decodeHints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE); 
         decodeHints.put(DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT, 
           Boolean.TRUE); 
         reader = new MultiFormatReader(); 

         turnOnFlashlight(globalCamera); 

         // pass surfaceView to CameraPreview 
         newCameraPreview = new CameraPreview(this, globalCamera) { 

          @Override 
          public boolean onTouchEvent(MotionEvent event) { 
           Log.d("ClassScanViewBarcodeActivity", 
             " onTouchEvent(MotionEvent event) "); 

           onTouchEvent = true; 
           globalCamera 
             .autoFocus(autoFocusCallbackForAutomaticScan); 

           return super.onTouchEvent(event); 
          } 

         }; 

         // pass CameraPreview to Layout 
         RelativeLayoutBarcodeScanner.addView(newCameraPreview); 


         // give reference SurfaceView to camera object 
         globalCamera.setPreviewDisplay(surfaceViewBarcodeScanner 
           .getHolder()); 

         // PREVIEW 
         if (cameraPreviewing != true) { 
          globalCamera.startPreview(); 
         } 

         Log.d("ClassScanViewBarcodeActivity", 
           "camera opened & previewing"); 
        } 
       }// end else ,check for front camera 
      }// end try 
      catch (Exception exc) { 

       // in case of exception release resources & cleanup 
       if (globalCamera != null) { 
        globalCamera.stopPreview(); 
        cameraPreviewing = false; 
        globalCamera.setPreviewCallback(null); 
        globalCamera.release(); 
        globalCamera = null; 
        options = null; 
        rotationMatrix90CounterClockWise = null; 
        reader = null; 

       } 
       Log.d("ClassScanViewBarcodeActivity initializeGlobalCamera() exception:", 
         exc.getMessage()); 
       exc.printStackTrace(); 
      }// end catch 

     }// end ini 

     /* this method detect whether the camera flashlight a.k.a torch feature is available to be turned on then turns on the light*/ 
     public void turnOnFlashlight(Camera camera) { 
      Log.d("ClassScanViewBarcodeActivity", 
        "turnOnFlashlight(Camera camera)"); 

      boolean flag = false; 
      Context context = null; 
      if (camera != null) { 
       Log.d("ClassScanViewBarcodeActivity", 
         "turnOnFlashlight() , FEATURE_CAMERA_FLASH: " + flag); 

       context = RelativeLayoutBarcodeScanner.getContext(); 
       if (context != null) { 
        flag = context.getPackageManager().hasSystemFeature(
          PackageManager.FEATURE_CAMERA_FLASH); 
        if (flag) { 
         Flash = camera.getParameters(); 
         Flash.setFlashMode("torch"); 

         camera.setParameters(Flash); 

        }// end if camera feature is available 

        else { 
         Log.d("ClassScanViewBarcodeActivity", 
           "turnOnFlashlight() , FEATURE_CAMERA_FLASH: " 
             + flag); 
        } 
       }// end if context not null 

      }// end camera not null 

     }// end turnOnFlashlight(Camera camera) 

     // onCreate, instantiates layouts & surfaceView used for video preview 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_barcode_vin_scanner); 
      Log.d("ClassScanViewBarcodeActivity", "onCreate "); 

      // create surfaceView for previewing of camera image 
      RelativeLayoutBarcodeScanner = (LinearLayout) findViewById(R.id.LayoutForPreview); 
      surfaceViewBarcodeScanner = (SurfaceView) findViewById(R.id.surfaceViewBarcodeScanner); 
      barcodeVinScannerToolbar = (LinearLayout) findViewById(R.id.linearLayoutToolbar); 



      initializeGlobalCamera(); 


      //*****TOOLBAR IS ADDED***** 

      if (RelativeLayoutBarcodeScanner!=null && barcodeVinScannerToolbar!=null) 
      { 

       //surfaceViewBarcodeScanner.addChildrenForAccessibility(list); 
       RelativeLayoutBarcodeScanner.addView(barcodeVinScannerToolbar);  

      } 


      // instantiate orientationEventListener 
      orientationEventListener = new OrientationEventListener(this, 
        SensorManager.SENSOR_DELAY_NORMAL) { 

       @Override 
       public void onOrientationChanged(int arg0) { 


        /* 
        latestScreenOrientation = ScreenUtility 
          .getScreenOrientation(RelativeLayoutBarcodeScanner.getContext()); 

        Log.d("ClassScanViewBarcodeActivity", 
          "latestScreenOrientation: " + latestScreenOrientation); 

        if (orientationEventListener.canDetectOrientation()) { 
         orientationEventListener.enable(); 
         Log.d("ClassScanViewBarcodeActivity", 
           "enabled orientationEventListener: " 
             + String.valueOf(orientationEventListener 
               .canDetectOrientation())); 
        } else { 
         Log.d("ClassScanViewBarcodeActivity", 
           "enabled orientationEventListener: " 
             + String.valueOf(orientationEventListener 
               .canDetectOrientation())); 
        } 
    */ 
       } 

      }; 



      handler = new Handler(); 




     }// end onCreate 


     @Override 
     protected void onResume() { 

      Log.d("ClassScanViewBarcodeActivity, onResume() globalCamera:", 
        String.valueOf(globalCamera)); 

      initializeGlobalCamera(); 


      //*****TOOLBAR IS ADDED***** 

      if (RelativeLayoutBarcodeScanner!=null && barcodeVinScannerToolbar!=null) 
      { 

       //surfaceViewBarcodeScanner.addChildrenForAccessibility(list); 
       RelativeLayoutBarcodeScanner.addView(barcodeVinScannerToolbar);  

      } 


      if (orientationEventListener != null) { 
       orientationEventListener.enable(); 
      } 

      super.onResume(); 
     } 

     @Override 
     protected void onStop() { 

      if (globalCamera != null) { 
       globalCamera.stopPreview(); 
       cameraPreviewing = false; 
       globalCamera.setPreviewCallback(null); 
       globalCamera.release(); 
       globalCamera = null; 
      } 

      if (orientationEventListener != null) { 
       orientationEventListener.disable(); 
      } 
      super.onStop(); 
     } 

     @Override 
     protected void onPause() { 
      if (globalCamera != null) { 
       globalCamera.stopPreview(); 
       cameraPreviewing = false; 
       globalCamera.setPreviewCallback(null); 
       globalCamera.release(); 
       globalCamera = null; 
       options = null; 
       rotationMatrix90CounterClockWise = null; 
       reader = null; 
      } 
      if (orientationEventListener != null) { 
       orientationEventListener.disable(); 
      } 
      super.onPause(); 
     }// end onPause() 

    //other irrelevant code was not included 

    }//end activity 

Покушение # 3, результат, экран замерзает, не конкретная ошибка или исключение докладывал:

enter image description here

Журнал ошибок:

enter image description here

** Если Инструмент GUI eclipse показывает желаемый внешний вид, чем почему панель инструментов все еще отсутствует? Я хотел бы иметь панель инструментов внизу, предпочтительно используя RelativeLayout без каких-либо сбоев или зависаний экрана. Любая помощь будет оценена.

Я использую Samsung Galaxy S3 для тестирования.

Спасибо. **

+0

Я уверен, что ваш макет прав, я просто испытал его на моем конце и отлично работает для меня. Я просто использовал код здесь: https: //github.com/commonsguy/cw-advandroid/blob/master/Camera/Preview/src/com/commonsware/android/camera/PreviewDemo.java Посмотрите на скриншот: http://goo.gl/8Z7oNU –

+0

У вас есть проблема, вероятно, в коде действия. –

ответ

0

Добавьте это в LinearLayout содержащий imageView

android:layout_alignParentBottom="true" 
+0

Я добавил свойство, которое вы упомянули, но все равно никакой разницы, я разместил новый xml выше. – cyber101

0

То, что вы действительно хотите не использовать RelativeLayout, но вместо того, чтобы использовать LinearLayout в качестве корня. Затем установите вес SurfaceView 1, что-то вроде:

<SurfaceView 
    android:id="@+id/surfaceViewBarcodeScanner" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_weight="1"/> 

<ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/scanner_bottom_left" /> 

    <ImageView 
     android:id="@+id/imageView2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/scanner_bottom_center_toolbar" /> 

    <ImageView 
     android:id="@+id/imageView3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/scanner_bottom_right_landscape_button" /> 
</LinearLayout> 

+0

Я добавил вес 1, но это не имело никакого значения, также я скорее сохранил его RelativeLayout, хотя я пробовал Linear, и это не имело значения. – cyber101

+0

см. Мой обновленный макет – cyber101

0

Вы забыли сказать surfaceView быть abovelinearLayout. Ваш код должен будет выглядеть примерно так:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <LinearLayout 
     android:id="@+id/linearLayoutToolbar" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" > 

     <ImageView 
      android:id="@+id/imageView1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:src="@drawable/scanner_bottom_left" /> 

     <ImageView 
      android:id="@+id/imageView2" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:src="@drawable/scanner_bottom_center_toolbar" /> 

     <ImageView 
      android:id="@+id/imageView3" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:src="@drawable/scanner_bottom_right_landscape_button" /> 
    </LinearLayout> 

    <SurfaceView 
     android:id="@+id/surfaceViewBarcodeScanner" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_above="@+id/linearLayoutToolbar" /> 

</RelativeLayout> 
+0

, я отредактировал свой макет и загрузил новый макет, однако все равно никакой разницы, панель инструментов не отображается. – cyber101

+0

, пожалуйста, см. Мой обновленный макет. – cyber101

+0

Попробуйте определить свой линейныйLayoutToolbar перед видом поверхности, как и в моем примере. – gian1200

0

Почему вы используете RelativeLayout как корневой макет, я думаю, что это гораздо проще использовать LinearLayou с layout_weight параметра в одном из детей смотреть:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 


<SurfaceView 
    android:layout_weight="1" 
    android:id="@+id/surfaceViewBarcodeScanner" 
    android:layout_width="match_parent" 
    android:layout_height="0dp" /> 

<!-- LinearLayout that contains toolbar that is divided into 3 sections horizontally --> 
<LinearLayout 
    android:id="@+id/linearLayoutToolbar" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/scanner_bottom_left" /> 

    <ImageView 
     android:id="@+id/imageView2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/scanner_bottom_center_toolbar" /> 

    <ImageView 
     android:id="@+id/imageView3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/scanner_bottom_right_landscape_button" /> 
</LinearLayout> 
</LinearLayout> 
0

попробуйте изменить расположение к этому:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/LayoutForPreview" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" 
android:screenOrientation="portrait" > 

<SurfaceView 
    android:id="@+id/surfaceViewBarcodeScanner" 
    android:layout_width="match_parent" 
    android:layout_height="0dp" 
    android:layout_gravity="top" 
    android:scaleType="fitXY" 
    android:layout_weight="1" /> 

<LinearLayout 
    android:id="@+id/linearLayoutToolbar" 
    android:layout_width="match_parent" 
    android:layout_height="0dp" 
    android:layout_weight=".1" 
    android:orientation="horizontal" 
    android:layout_gravity="bottom" > 

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:scaleType="fitXY" 
     android:src="@drawable/scanner_bottom_left" /> 

    <ImageView 
     android:id="@+id/imageView2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="0.68" 
     android:scaleType="fitXY" 
     android:src="@drawable/scanner_bottom_center_toolbar" /> 

    <ImageView 
     android:id="@+id/imageView3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:scaleType="fitXY" 
     android:src="@drawable/scanner_bottom_right_landscape_button" /> 
</LinearLayout> 

0

Я вижу несколько метров istakes в вашем исходном XML 1.В SurfaceView вы используете:

android:layout_above="@+id/linearLayoutToolbar" 

Вы должны использовать @ + идентификатор при создании Id, но если вы хотите сделать ссылку, вы должны делать только @id так:

android:layout_above="@id/linearLayoutToolbar" 

2. Вы не можете сделать ссылку на другой объект, который еще не создан! Таким образом, вы должны поставить SurfaceView ниже де LinearLayout так:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/LayoutForPreview" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" 
android:screenOrientation="portrait" > 

<LinearLayout 
    android:id="@+id/linearLayoutToolbar" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentBottom="true" 
    android:orientation="horizontal" > 

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:scaleType="fitXY" 
     android:src="@drawable/scanner_bottom_left" /> 

    <ImageView 
     android:id="@+id/imageView2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="0.68" 
     android:scaleType="fitXY" 
     android:src="@drawable/scanner_bottom_center_toolbar" /> 

    <ImageView 
     android:id="@+id/imageView3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:scaleType="fitXY" 
     android:src="@drawable/scanner_bottom_right_landscape_button" /> 
</LinearLayout> 

<SurfaceView 
    android:id="@+id/surfaceViewBarcodeScanner" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_above="@id/linearLayoutToolbar" 
    android:layout_gravity="top" 
    android:scaleType="fitXY" /> 

</RelativeLayout> 

3. Вы должны добавить вес к вашей 3 ImageViews так:

android:layout_weight="1" 
1

Вы хотели что-то вроде этого?

enter image description here

макета я использовал:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    > 
    <LinearLayout 
     android:id="@+id/linearLayoutToolbar" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     > 
     <ImageView 
      android:id="@+id/imageView1" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:gravity="center" 
      android:src="@drawable/ic_launcher" 
     /> 
     <ImageView 
      android:id="@+id/imageView2" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:gravity="center" 
      android:src="@drawable/ic_launcher" 
     /> 
     <ImageView 
      android:id="@+id/imageView3" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:gravity="center" 
      android:src="@drawable/ic_launcher" 
     /> 
    </LinearLayout> 
    <SurfaceView 
     android:id="@+id/surfaceViewBarcodeScanner" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_above="@+id/linearLayoutToolbar" 
    /> 
</RelativeLayout> 

Пожалуйста, обратите внимание, что, так как у меня не было изображения в моем разрешении/вытяжке папки, я заменил их ic_launcher ,

Также обратите внимание, что я использовал ldpi устройство работает Froyo (API level 2.2). Вот почему изображение меньше вашего, и пользовательский интерфейс отличается незначительно (...). Во всяком случае, работает при каждом разрешении и с каждой версией os.

0

Некоторые небольшие изменения в исходном макете приведут к удалению ошибки. Вам нужно использовать android:layout_height="0dp", определяя, что 0dp поможет вашему представлению поверхности соответствовать вашему экрану.

<SurfaceView 
    android:id="@+id/surfaceViewBarcodeScanner" 
    android:layout_width="match_parent" 
    android:layout_height="0dp" 
    android:layout_above="@+id/linearLayoutToolbar" 
    /> 

И я не нашел использование атрибута ниже в SurfaceView.

android:layout_gravity="top" 
    android:scaleType="fitXY" 

заказ этот макет конструкции, то как android:layout_height="0dp" работает, и как android:layout_width="0dp" работы.

0

Я использовал такие макеты во многих приложениях, и вот как должен быть ваш макет. Нет трюки, не молясь на удачу, это не только чистый, счастливый, и всегда работает способ ее достижение

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:screenOrientation="portrait" > 

    <SurfaceView 
     android:id="@+id/surfaceViewBarcodeScanner" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_above="@+id/linearLayoutToolbar" 
     android:layout_alignParentTop="true" /> 

    <LinearLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/linearLayoutToolbar" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:orientation="horizontal" > 

     <ImageView 
      android:id="@+id/imageView1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:scaleType="fitXY" 
      android:src="@drawable/scanner_bottom_left" /> 

     <ImageView 
      android:id="@+id/imageView2" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_weight="0.68" 
      android:scaleType="fitXY" 
      android:src="@drawable/scanner_bottom_center_toolbar" /> 

     <ImageView 
      android:id="@+id/imageView3" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:scaleType="fitXY" 
      android:src="@drawable/scanner_bottom_right_landscape_button" /> 
    </LinearLayout> 

</RelativeLayout> 

here you have a preview on one of my apps.

Опубликованный код адаптирована к вашему поэтому копировать/вставить будет делать Это. обратите внимание, что все это в простом файле, поэтому вам нужно немного изменить свою активность.

Смежные вопросы