public void checkFileSize(File file) {
   if (FileUtils.isFileOversized(file)) {
     this.notifyWarning(
         StringUtils.getStringRobust(
             getContext(), R.string.attachment_oversized, FileUtils.getFileSize(file) + ""));
   }
 }
 private void Reset() {
   savepointImage.delete();
   if (!OPTION_SIGNATURE.equals(loadOption) && refImage != null && refImage.exists()) {
     FileUtils.copyFile(refImage, savepointImage);
   }
   drawView.reset();
   drawView.invalidate();
 }
 public void resetImage(int w, int h) {
   if (mBackgroundBitmapFile.exists()) {
     mBitmap =
         FileUtils.getBitmapScaledToDisplay(mBackgroundBitmapFile, w, h)
             .copy(Bitmap.Config.ARGB_8888, true);
     // mBitmap =
     // Bitmap.createScaledBitmap(BitmapFactory.decodeFile(mBackgroundBitmapFile.getPath()),
     // w, h, true);
     mCanvas = new Canvas(mBitmap);
   } else {
     mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
     mCanvas = new Canvas(mBitmap);
     mCanvas.drawColor(0xFFFFFFFF);
     if (isSignature) drawSignLine();
   }
 }
    @SuppressWarnings("unchecked")
    public ListMultiWidget(Context context, FormEntryPrompt prompt, boolean displayLabel) {
        super(context, prompt);

        mItems = prompt.getSelectChoices();
        mCheckboxes = new ArrayList<CheckBox>();
        mPrompt = prompt;

        // Layout holds the horizontal list of buttons
        LinearLayout buttonLayout = new LinearLayout(context);

        Vector<Selection> ve = new Vector<Selection>();
        if (prompt.getAnswerValue() != null) {
            ve = (Vector<Selection>) prompt.getAnswerValue().getValue();
        }

        if (mItems != null) {
            for (int i = 0; i < mItems.size(); i++) {
                CheckBox c = new CheckBox(getContext());
                c.setTag(Integer.valueOf(i));
                c.setId(QuestionWidget.newUniqueId());
                c.setFocusable(!prompt.isReadOnly());
                c.setEnabled(!prompt.isReadOnly());
                for (int vi = 0; vi < ve.size(); vi++) {
                    // match based on value, not key
                    if (mItems.get(i).getValue().equals(ve.elementAt(vi).getValue())) {
                        c.setChecked(true);
                        break;
                    }

                }
                mCheckboxes.add(c);

                // when clicked, check for readonly before toggling
                c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (!mCheckboxInit && mPrompt.isReadOnly()) {
                            if (buttonView.isChecked()) {
                                buttonView.setChecked(false);
                               	Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.deselect",
                            			mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
                            } else {
                                buttonView.setChecked(true);
                               	Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.select",
                            			mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
                            }
                        }
                    }
                });

                String imageURI = null;
                imageURI =
                    prompt.getSpecialFormSelectChoiceText(mItems.get(i),
                        FormEntryCaption.TEXT_FORM_IMAGE);

                // build image view (if an image is provided)
                ImageView mImageView = null;
                TextView mMissingImage = null;

                final int labelId = QuestionWidget.newUniqueId();

                // Now set up the image view
                String errorMsg = null;
                if (imageURI != null) {
                    try {
                        String imageFilename =
                            ReferenceManager._().DeriveReference(imageURI).getLocalURI();
                        final File imageFile = new File(imageFilename);
                        if (imageFile.exists()) {
                            Bitmap b = null;
                            try {
                                Display display =
                                    ((WindowManager) getContext().getSystemService(
                                        Context.WINDOW_SERVICE)).getDefaultDisplay();
                                int screenWidth = display.getWidth();
                                int screenHeight = display.getHeight();
                                b =
                                    FileUtils.getBitmapScaledToDisplay(imageFile, screenHeight,
                                        screenWidth);
                            } catch (OutOfMemoryError e) {
                                errorMsg = "ERROR: " + e.getMessage();
                            }

                            if (b != null) {
                                mImageView = new ImageView(getContext());
                                mImageView.setPadding(2, 2, 2, 2);
                                mImageView.setAdjustViewBounds(true);
                                mImageView.setImageBitmap(b);
                                mImageView.setId(labelId);
                            } else if (errorMsg == null) {
                                // An error hasn't been logged and loading the image failed, so it's
                                // likely
                                // a bad file.
                                errorMsg = getContext().getString(R.string.file_invalid, imageFile);

                            }
                        } else if (errorMsg == null) {
                            // An error hasn't been logged. We should have an image, but the file
                            // doesn't
                            // exist.
                            errorMsg = getContext().getString(R.string.file_missing, imageFile);
                        }

                        if (errorMsg != null) {
                            // errorMsg is only set when an error has occured
                            Log.e(t, errorMsg);
                            mMissingImage = new TextView(getContext());
                            mMissingImage.setText(errorMsg);

                            mMissingImage.setPadding(2, 2, 2, 2);
                            mMissingImage.setId(labelId);
                        }
                    } catch (InvalidReferenceException e) {
                        Log.e(t, "image invalid reference exception");
                        e.printStackTrace();
                    }
                } else {
                    // There's no imageURI listed, so just ignore it.
                }

                // build text label. Don't assign the text to the built in label to he
                // button because it aligns horizontally, and we want the label on top
                TextView label = new TextView(getContext());
                label.setText(prompt.getSelectChoiceText(mItems.get(i)));
                label.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
                label.setGravity(Gravity.CENTER_HORIZONTAL);
                if (!displayLabel) {
                    label.setVisibility(View.GONE);
                }

                // answer layout holds the label text/image on top and the radio button on bottom
                RelativeLayout answer = new RelativeLayout(getContext());
                RelativeLayout.LayoutParams headerParams =
                        new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                headerParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                headerParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
                
                RelativeLayout.LayoutParams buttonParams =
                        new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);

                if (mImageView != null) {
                	mImageView.setScaleType(ScaleType.CENTER);
                    if (!displayLabel) {
                        mImageView.setVisibility(View.GONE);
                    }
                    answer.addView(mImageView, headerParams);
                } else if (mMissingImage != null) {
                    answer.addView(mMissingImage, headerParams);
                } else {
                    if (displayLabel) {
                    	label.setId(labelId);
                        answer.addView(label, headerParams);
                    }

                }
                if (displayLabel) {
                	buttonParams.addRule(RelativeLayout.BELOW, labelId);
                }
                answer.addView(c, buttonParams);
                answer.setPadding(4, 0, 4, 0);

                // /Each button gets equal weight
                LinearLayout.LayoutParams answerParams =
                    new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                            LayoutParams.WRAP_CONTENT);
                answerParams.weight = 1;

                buttonLayout.addView(answer, answerParams);

            }
        }

        // Align the buttons so that they appear horizonally and are right justified
        // buttonLayout.setGravity(Gravity.RIGHT);
        buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
        // LinearLayout.LayoutParams params = new
        // LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        // buttonLayout.setLayoutParams(params);

        // The buttons take up the right half of the screen
        LinearLayout.LayoutParams buttonParams =
            new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        buttonParams.weight = 1;

        questionLayout.addView(buttonLayout, buttonParams);
        addView(questionLayout);

    }
  public AnnotateWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);

    mInstanceFolder = Collect.getInstance().getFormController().getInstancePath().getParent();

    setOrientation(LinearLayout.VERTICAL);

    TableLayout.LayoutParams params = new TableLayout.LayoutParams();
    params.setMargins(7, 5, 7, 5);

    mErrorTextView = new TextView(context);
    mErrorTextView.setId(QuestionWidget.newUniqueId());
    mErrorTextView.setText("Selected file is not a valid image");

    // setup capture button
    mCaptureButton = new Button(getContext());
    mCaptureButton.setId(QuestionWidget.newUniqueId());
    mCaptureButton.setText(getContext().getString(R.string.capture_image));
    mCaptureButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mCaptureButton.setPadding(20, 20, 20, 20);
    mCaptureButton.setEnabled(!prompt.isReadOnly());
    mCaptureButton.setLayoutParams(params);

    // launch capture intent on click
    mCaptureButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Collect.getInstance()
                .getActivityLogger()
                .logInstanceAction(this, "captureButton", "click", mPrompt.getIndex());
            mErrorTextView.setVisibility(View.GONE);
            Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            // We give the camera an absolute filename/path where to put the
            // picture because of bug:
            // http://code.google.com/p/android/issues/detail?id=1480
            // The bug appears to be fixed in Android 2.0+, but as of feb 2,
            // 2010, G1 phones only run 1.6. Without specifying the path the
            // images returned by the camera in 1.6 (and earlier) are ~1/4
            // the size. boo.

            // if this gets modified, the onActivityResult in
            // FormEntyActivity will also need to be updated.
            i.putExtra(
                android.provider.MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(Collect.TMPFILE_PATH)));
            try {
              Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
              ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.IMAGE_CAPTURE);
            } catch (ActivityNotFoundException e) {
              Toast.makeText(
                      getContext(),
                      getContext().getString(R.string.activity_not_found, "image capture"),
                      Toast.LENGTH_SHORT)
                  .show();
              Collect.getInstance().getFormController().setIndexWaitingForData(null);
            }
          }
        });

    // setup chooser button
    mChooseButton = new Button(getContext());
    mChooseButton.setId(QuestionWidget.newUniqueId());
    mChooseButton.setText(getContext().getString(R.string.choose_image));
    mChooseButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mChooseButton.setPadding(20, 20, 20, 20);
    mChooseButton.setEnabled(!prompt.isReadOnly());
    mChooseButton.setLayoutParams(params);

    // launch capture intent on click
    mChooseButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Collect.getInstance()
                .getActivityLogger()
                .logInstanceAction(this, "chooseButton", "click", mPrompt.getIndex());
            mErrorTextView.setVisibility(View.GONE);
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.setType("image/*");

            try {
              Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
              ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.IMAGE_CHOOSER);
            } catch (ActivityNotFoundException e) {
              Toast.makeText(
                      getContext(),
                      getContext().getString(R.string.activity_not_found, "choose image"),
                      Toast.LENGTH_SHORT)
                  .show();
              Collect.getInstance().getFormController().setIndexWaitingForData(null);
            }
          }
        });

    // setup Blank Image Button
    mAnnotateButton = new Button(getContext());
    mAnnotateButton.setId(QuestionWidget.newUniqueId());
    mAnnotateButton.setText(getContext().getString(R.string.markup_image));
    mAnnotateButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mAnnotateButton.setPadding(20, 20, 20, 20);
    mAnnotateButton.setEnabled(false);
    mAnnotateButton.setLayoutParams(params);
    // launch capture intent on click
    mAnnotateButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Collect.getInstance()
                .getActivityLogger()
                .logInstanceAction(this, "annotateButton", "click", mPrompt.getIndex());
            launchAnnotateActivity();
          }
        });

    // finish complex layout
    addView(mCaptureButton);
    addView(mChooseButton);
    addView(mAnnotateButton);
    addView(mErrorTextView);

    // and hide the capture, choose and annotate button if read-only
    if (prompt.isReadOnly()) {
      mCaptureButton.setVisibility(View.GONE);
      mChooseButton.setVisibility(View.GONE);
      mAnnotateButton.setVisibility(View.GONE);
    }
    mErrorTextView.setVisibility(View.GONE);

    // retrieve answer from data model and update ui
    mBinaryName = prompt.getAnswerText();

    // Only add the imageView if the user has taken a picture
    if (mBinaryName != null) {
      if (!prompt.isReadOnly()) {
        mAnnotateButton.setEnabled(true);
      }
      mImageView = new ImageView(getContext());
      mImageView.setId(QuestionWidget.newUniqueId());
      Display display =
          ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
              .getDefaultDisplay();
      int screenWidth = display.getWidth();
      int screenHeight = display.getHeight();

      File f = new File(mInstanceFolder + File.separator + mBinaryName);

      if (f.exists()) {
        Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f, screenHeight, screenWidth);
        if (bmp == null) {
          mErrorTextView.setVisibility(View.VISIBLE);
        }
        mImageView.setImageBitmap(bmp);
      } else {
        mImageView.setImageBitmap(null);
      }

      mImageView.setPadding(10, 10, 10, 10);
      mImageView.setAdjustViewBounds(true);
      mImageView.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              Collect.getInstance()
                  .getActivityLogger()
                  .logInstanceAction(this, "viewImage", "click", mPrompt.getIndex());
              launchAnnotateActivity();
            }
          });

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

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow()
        .setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    Bundle extras = getIntent().getExtras();

    if (extras == null) {
      loadOption = OPTION_DRAW;
      refImage = null;
      savepointImage = new File(Collect.TMPDRAWFILE_PATH);
      savepointImage.delete();
      output = new File(Collect.TMPFILE_PATH);
    } else {
      loadOption = extras.getString(OPTION);
      if (loadOption == null) {
        loadOption = OPTION_DRAW;
      }
      // refImage can also be present if resuming a drawing
      Uri uri = (Uri) extras.get(REF_IMAGE);
      if (uri != null) {
        refImage = new File(uri.getPath());
      }
      String savepoint = extras.getString(SAVEPOINT_IMAGE);
      if (savepoint != null) {
        savepointImage = new File(savepoint);
        if (!savepointImage.exists() && refImage != null && refImage.exists()) {
          FileUtils.copyFile(refImage, savepointImage);
        }
      } else {
        savepointImage = new File(Collect.TMPDRAWFILE_PATH);
        savepointImage.delete();
        if (refImage != null && refImage.exists()) {
          FileUtils.copyFile(refImage, savepointImage);
        }
      }
      uri = (Uri) extras.get(EXTRA_OUTPUT);
      if (uri != null) {
        output = new File(uri.getPath());
      } else {
        output = new File(Collect.TMPFILE_PATH);
      }
    }

    // At this point, we have:
    // loadOption -- type of activity (draw, signature, annotate)
    // refImage -- original image to work with
    // savepointImage -- drawing to use as a starting point (may be copy of
    // original)
    // output -- where the output should be written

    if (OPTION_SIGNATURE.equals(loadOption)) {
      // set landscape
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
      alertTitleString = getString(R.string.quit_application, getString(R.string.sign_button));
    } else if (OPTION_ANNOTATE.equals(loadOption)) {
      alertTitleString = getString(R.string.quit_application, getString(R.string.markup_image));
    } else {
      alertTitleString = getString(R.string.quit_application, getString(R.string.draw_image));
    }

    setTitle(getString(R.string.app_name) + " > " + getString(R.string.draw_image));

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    RelativeLayout v = (RelativeLayout) inflater.inflate(R.layout.draw_layout, null);
    LinearLayout ll = (LinearLayout) v.findViewById(R.id.drawViewLayout);

    drawView = new DrawView(this, OPTION_SIGNATURE.equals(loadOption), savepointImage);

    ll.addView(drawView);

    setContentView(v);

    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setDither(true);
    paint.setColor(currentColor);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeJoin(Paint.Join.ROUND);
    paint.setStrokeWidth(10);

    pointPaint = new Paint();
    pointPaint.setAntiAlias(true);
    pointPaint.setDither(true);
    pointPaint.setColor(currentColor);
    pointPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    pointPaint.setStrokeWidth(10);

    btnDrawColor = (Button) findViewById(R.id.btnSelectColor);
    btnDrawColor.setTextColor(getInverseColor(currentColor));
    btnDrawColor.getBackground().setColorFilter(currentColor, PorterDuff.Mode.SRC_ATOP);
    btnDrawColor.setText(getString(R.string.set_color));
    btnDrawColor.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            Collect.getInstance()
                .getActivityLogger()
                .logInstanceAction(
                    DrawActivity.this,
                    "setColorButton",
                    "click",
                    Collect.getInstance().getFormController().getFormIndex());
            ColorPickerDialog cpd =
                new ColorPickerDialog(
                    DrawActivity.this,
                    new ColorPickerDialog.OnColorChangedListener() {
                      public void colorChanged(String key, int color) {
                        btnDrawColor.setTextColor(getInverseColor(color));
                        btnDrawColor
                            .getBackground()
                            .setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
                        currentColor = color;
                        paint.setColor(color);
                        pointPaint.setColor(color);
                      }
                    },
                    "key",
                    currentColor,
                    currentColor,
                    getString(R.string.select_drawing_color));
            cpd.show();
          }
        });
    btnFinished = (Button) findViewById(R.id.btnFinishDraw);
    btnFinished.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Collect.getInstance()
                .getActivityLogger()
                .logInstanceAction(
                    DrawActivity.this,
                    "saveAndCloseButton",
                    "click",
                    Collect.getInstance().getFormController().getFormIndex());
            SaveAndClose();
          }
        });
    btnReset = (Button) findViewById(R.id.btnResetDraw);
    btnReset.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Collect.getInstance()
                .getActivityLogger()
                .logInstanceAction(
                    DrawActivity.this,
                    "resetButton",
                    "click",
                    Collect.getInstance().getFormController().getFormIndex());
            Reset();
          }
        });
    btnCancel = (Button) findViewById(R.id.btnCancelDraw);
    btnCancel.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            /*				Collect.getInstance()
            .getActivityLogger()
            .logInstanceAction(
            		DrawActivity.this,
            		"cancelAndCloseButton",
            		"click",
            		Collect.getInstance().getFormController()
            				.getFormIndex());*/
            CancelAndClose();
          }
        });
  }
    @SuppressWarnings("unchecked")
    public GridMultiWidget(Context context, FormEntryPrompt prompt, int numColumns) {
        super(context, prompt);
        mItems = prompt.getSelectChoices();
        mPrompt = prompt;

        selected = new boolean[mItems.size()];
        choices = new String[mItems.size()];
        gridview = new GridView(context);
        imageViews = new ImageView[mItems.size()];
        maxColumnWidth = -1;
        this.numColumns = numColumns;
        for (int i = 0; i < mItems.size(); i++) {
            imageViews[i] = new ImageView(getContext());
        }

        // Build view
        for (int i = 0; i < mItems.size(); i++) {
            SelectChoice sc = mItems.get(i);
            // Read the image sizes and set maxColumnWidth. This allows us to make sure all of our
            // columns are going to fit
            String imageURI =
                prompt.getSpecialFormSelectChoiceText(sc, FormEntryCaption.TEXT_FORM_IMAGE);

            if (imageURI != null) {
                choices[i] = imageURI;

                String imageFilename;
                try {
                    imageFilename = ReferenceManager._().DeriveReference(imageURI).getLocalURI();
                    final File imageFile = new File(imageFilename);
                    if (imageFile.exists()) {
                        Display display =
                            ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
                                    .getDefaultDisplay();
                        int screenWidth = display.getWidth();
                        int screenHeight = display.getHeight();
                        Bitmap b =
                            FileUtils
                                    .getBitmapScaledToDisplay(imageFile, screenHeight, screenWidth);
                        if (b != null) {

                            if (b.getWidth() > maxColumnWidth) {
                                maxColumnWidth = b.getWidth();
                            }

                        }
                    }
                } catch (InvalidReferenceException e) {
                    Log.e("GridWidget", "image invalid reference exception");
                    e.printStackTrace();
                }

            } else {
                choices[i] = prompt.getSelectChoiceText(sc);
            }

        }

        // Use the custom image adapter and initialize the grid view
        ImageAdapter ia = new ImageAdapter(getContext(), choices);
        gridview.setAdapter(ia);
        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                if (selected[position]) {
                    selected[position] = false;
                    imageViews[position].setBackgroundColor(Color.WHITE);
                   	Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.deselect", 
                			mItems.get(position).getValue(), mPrompt.getIndex());

                } else {
                    selected[position] = true;
                    imageViews[position].setBackgroundColor(Color.rgb(orangeRedVal, orangeGreenVal,
                        orangeBlueVal));
                   	Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.select", 
                			mItems.get(position).getValue(), mPrompt.getIndex());
                }

            }
        });

        // Read the screen dimensions and fit the grid view to them. It is important that the grid
        // view
        // knows how far out it can stretch.
        Display display =
            ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay();
        int screenWidth = display.getWidth();
        int screenHeight = display.getHeight();
        GridView.LayoutParams params = new GridView.LayoutParams(screenWidth - 5, screenHeight - 5);
        gridview.setLayoutParams(params);

        // Use the user's choice for num columns, otherwise automatically decide.
        if (numColumns > 0) {
            gridview.setNumColumns(numColumns);
        } else {
            gridview.setNumColumns(GridView.AUTO_FIT);
        }

        gridview.setColumnWidth(maxColumnWidth);
        gridview.setHorizontalSpacing(2);
        gridview.setVerticalSpacing(2);
        gridview.setGravity(Gravity.LEFT);
        gridview.setStretchMode(GridView.NO_STRETCH);

        // Fill in answer
        IAnswerData answer = prompt.getAnswerValue();
        Vector<Selection> ve;
        if ((answer == null) || (answer.getValue() == null)) {
            ve = new Vector<Selection>();
        } else {
            ve = (Vector<Selection>) answer.getValue();
        }

        for (int i = 0; i < choices.length; ++i) {

            String value = mItems.get(i).getValue();
            boolean found = false;
            for (Selection s : ve) {
                if (value.equals(s.getValue())) {
                    found = true;
                    break;
                }
            }

            selected[i] = found;
            if (selected[i]) {
                imageViews[i].setBackgroundColor(Color.rgb(orangeRedVal, orangeGreenVal,
                    orangeBlueVal));
            } else {
                imageViews[i].setBackgroundColor(Color.WHITE);
            }
        }

        addView(gridview);
    }
        // create a new ImageView for each item referenced by the Adapter
        public View getView(int position, View convertView, ViewGroup parent) {
            String imageURI = choices[position];

            // It is possible that an imageview already exists and has been updated
            // by updateViewAfterAnswer
            ImageView mImageView = null;
            if (imageViews[position] != null) {
                mImageView = imageViews[position];
            }
            TextView mMissingImage = null;

            String errorMsg = null;
            if (imageURI != null) {
                try {
                    String imageFilename =
                        ReferenceManager._().DeriveReference(imageURI).getLocalURI();
                    final File imageFile = new File(imageFilename);
                    if (imageFile.exists()) {
                        Display display =
                            ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
                                    .getDefaultDisplay();
                        int screenWidth = display.getWidth();
                        int screenHeight = display.getHeight();
                        Bitmap b =
                            FileUtils
                                    .getBitmapScaledToDisplay(imageFile, screenHeight, screenWidth);
                        if (b != null) {

                            if (mImageView == null) {
                                mImageView = new ImageView(getContext());
                                mImageView.setBackgroundColor(Color.WHITE);
                            }

                            mImageView.setPadding(3, 3, 3, 3);
                            mImageView.setImageBitmap(b);

                            imageViews[position] = mImageView;

                        } else {
                            // Loading the image failed, so it's likely a bad file.
                            errorMsg = getContext().getString(R.string.file_invalid, imageFile);
                        }
                    } else {
                        // We should have an image, but the file doesn't exist.
                        errorMsg = getContext().getString(R.string.file_missing, imageFile);
                    }

                    if (errorMsg != null) {
                        // errorMsg is only set when an error has occurred
                        Log.e("GridWidget", errorMsg);
                        mMissingImage = new TextView(getContext());
                        mMissingImage.setText(errorMsg);
                        mMissingImage.setPadding(10, 10, 10, 10);
                    }
                } catch (InvalidReferenceException e) {
                    Log.e("GridWidget", "image invalid reference exception");
                    e.printStackTrace();
                }
            } else {
                // There's no imageURI listed, so just ignore it.
            }

            if (mImageView != null) {
                mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
                return mImageView;
            } else {
                return mMissingImage;
            }
        }
Пример #9
0
    public void setAVT(FormIndex index, String selectionDesignator, TextView text, String audioURI, String imageURI, String videoURI,
            final String bigImageURI) {
    	mSelectionDesignator = selectionDesignator;
    	mIndex = index;
        mView_Text = text;
        mView_Text.setId(QuestionWidget.newUniqueId());
        mVideoURI = videoURI;

        // Layout configurations for our elements in the relative layout
        RelativeLayout.LayoutParams textParams =
            new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        RelativeLayout.LayoutParams audioParams =
            new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        RelativeLayout.LayoutParams imageParams =
            new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        RelativeLayout.LayoutParams videoParams =
            new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        // First set up the audio button
        if (audioURI != null) {
            // An audio file is specified
            mAudioButton = new AudioButton(getContext(), mIndex, mSelectionDesignator, audioURI);
            mAudioButton.setId(QuestionWidget.newUniqueId()); // random ID to be used by the
                                                                      // relative layout.
        } else {
            // No audio file specified, so ignore.
        }

        // Then set up the video button
        if (videoURI != null) {
            // An video file is specified
            mVideoButton = new ImageButton(getContext());
            Bitmap b =
                    BitmapFactory.decodeResource(getContext().getResources(),
                        android.R.drawable.ic_media_play);
            mVideoButton.setImageBitmap(b);
            mVideoButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                	Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick", "playVideoPrompt"+mSelectionDesignator, mIndex);
                	MediaLayout.this.playVideo();
                }

            });
            mVideoButton.setId(QuestionWidget.newUniqueId());
        } else {
            // No video file specified, so ignore.
        }

        // Now set up the image view
        String errorMsg = null;
        final int imageId = QuestionWidget.newUniqueId();
        if (imageURI != null) {
            try {
                String imageFilename = ReferenceManager._().DeriveReference(imageURI).getLocalURI();
                final File imageFile = new File(imageFilename);
                if (imageFile.exists()) {
                    Display display =
                        ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
                                .getDefaultDisplay();
                    int screenWidth = display.getWidth();
                    int screenHeight = display.getHeight();
                    Bitmap b = FileUtils.getBitmapScaledToDisplay(imageFile, screenHeight, screenWidth);
                    if (b != null) {
                        mImageView = new ImageView(getContext());
                        mImageView.setPadding(2, 2, 2, 2);
                        mImageView.setBackgroundColor(Color.WHITE);
                        mImageView.setImageBitmap(b);
                        mImageView.setId(imageId);

                        if (bigImageURI != null) {
                            mImageView.setOnClickListener(new OnClickListener() {
                            	String bigImageFilename = ReferenceManager._()
                                        .DeriveReference(bigImageURI).getLocalURI();
                                File bigImage = new File(bigImageFilename);


                                @Override
                                public void onClick(View v) {
                                	Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick", "showImagePromptBigImage"+mSelectionDesignator, mIndex);

                                    Intent i = new Intent("android.intent.action.VIEW");
                                    i.setDataAndType(Uri.fromFile(bigImage), "image/*");
                                    try {
                                        getContext().startActivity(i);
                                    } catch (ActivityNotFoundException e) {
                                        Toast.makeText(
                                            getContext(),
                                            getContext().getString(R.string.activity_not_found,
                                                "view image"), Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    } else {
                        // Loading the image failed, so it's likely a bad file.
                        errorMsg = getContext().getString(R.string.file_invalid, imageFile);
                    }
                } else {
                    // We should have an image, but the file doesn't exist.
                    errorMsg = getContext().getString(R.string.file_missing, imageFile);
                }

                if (errorMsg != null) {
                    // errorMsg is only set when an error has occurred
                    Log.e(t, errorMsg);
                    mMissingImage = new TextView(getContext());
                    mMissingImage.setText(errorMsg);
                    mMissingImage.setPadding(10, 10, 10, 10);
                    mMissingImage.setId(imageId);
                }
            } catch (InvalidReferenceException e) {
                Log.e(t, "image invalid reference exception");
                e.printStackTrace();
            }
        } else {
            // There's no imageURI listed, so just ignore it.
        }

        // e.g., for TextView that flag will be true
        boolean isNotAMultipleChoiceField = !RadioButton.class.isAssignableFrom(text.getClass()) && !CheckBox.class.isAssignableFrom(text.getClass());

        // Determine the layout constraints...
        // Assumes LTR, TTB reading bias!
        if (mView_Text.getText().length() == 0 && (mImageView != null || mMissingImage != null)) {
            // No text; has image. The image is treated as question/choice icon.
            // The Text view may just have a radio button or checkbox. It
            // needs to remain in the layout even though it is blank.
            //
            // The image view, as created above, will dynamically resize and
            // center itself. We want it to resize but left-align itself
            // in the resized area and we want a white background, as otherwise
            // it will show a grey bar to the right of the image icon.
            if (mImageView != null) {
                mImageView.setScaleType(ScaleType.FIT_START);
            }
            //
            // In this case, we have:
            // Text upper left; image upper, left edge aligned with text right edge;
            // audio upper right; video below audio on right.
            textParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            if (isNotAMultipleChoiceField) {
                imageParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
            } else {
                imageParams.addRule(RelativeLayout.RIGHT_OF, mView_Text.getId());
            }
            imageParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            if (mAudioButton != null && mVideoButton == null) {
                audioParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                imageParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
            } else if (mAudioButton == null && mVideoButton != null) {
                videoParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                imageParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
            } else if (mAudioButton != null && mVideoButton != null) {
                audioParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                imageParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
                videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                videoParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
                imageParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
            } else {
                // the image will implicitly scale down to fit within parent...
                // no need to bound it by the width of the parent...
                if (!isNotAMultipleChoiceField) {
                    imageParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                }
            }
            imageParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        } else {
            // We have a non-blank text label -- image is below the text.
            // In this case, we want the image to be centered...
            if (mImageView != null) {
                mImageView.setScaleType(ScaleType.FIT_START);
            }
            //
            // Text upper left; audio upper right; video below audio on right.
            // image below text, audio and video buttons; left-aligned with text.
            textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            textParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            if (mAudioButton != null && mVideoButton == null) {
                audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
          } else if (mAudioButton == null && mVideoButton != null) {
                videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                textParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
            } else if (mAudioButton != null && mVideoButton != null) {
                audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
                videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                videoParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
            } else {
                textParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            }

            if (mImageView != null || mMissingImage != null) {
                imageParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                imageParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
                imageParams.addRule(RelativeLayout.BELOW, mView_Text.getId());
            } else {
                textParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            }
        }

        addView(mView_Text, textParams);
        if (mAudioButton != null)
            addView(mAudioButton, audioParams);
        if (mVideoButton != null)
            addView(mVideoButton, videoParams);
        if (mImageView != null)
            addView(mImageView, imageParams);
        else if (mMissingImage != null)
            addView(mMissingImage, imageParams);
    }