// Override QuestionWidget's add question text. Build it the same
    // but add it to the questionLayout
    protected void addQuestionText(FormEntryPrompt p) {

        // Add the text view. Textview always exists, regardless of whether there's text.
    	TextView questionText = new TextView(getContext());
        questionText.setText(p.getLongText());
        questionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
        questionText.setTypeface(null, Typeface.BOLD);
        questionText.setPadding(0, 0, 0, 7);
        questionText.setId(QuestionWidget.newUniqueId()); // assign random id

        // Wrap to the size of the parent view
        questionText.setHorizontallyScrolling(false);

        if (p.getLongText() == null) {
            questionText.setVisibility(GONE);
        }

        // Put the question text on the left half of the screen
        LinearLayout.LayoutParams labelParams =
            new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        labelParams.weight = 1;

        questionLayout = new LinearLayout(getContext());
        questionLayout.setOrientation(LinearLayout.HORIZONTAL);

        questionLayout.addView(questionText, labelParams);
    }
Пример #2
0
  public StringWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);
    mAnswer = new EditText(context);

    mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);

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

    // capitalize the first letter of the sentence
    mAnswer.setKeyListener(new TextKeyListener(Capitalize.SENTENCES, false));

    // needed to make long read only text scroll
    mAnswer.setHorizontallyScrolling(false);
    mAnswer.setSingleLine(false);

    if (prompt != null) {
      mReadOnly = prompt.isReadOnly();
      String s = prompt.getAnswerText();
      if (s != null) {
        mAnswer.setText(s);
      }

      if (mReadOnly) {
        mAnswer.setBackgroundDrawable(null);
        mAnswer.setFocusable(false);
        mAnswer.setClickable(false);
      }
    }

    addView(mAnswer);
  }
  private void fillGridRow(
      FormEntryController formEntryController, GridRow gridRow, int columnIndex) throws Exception {
    FormEntryPrompt currentQuestionPrompt = formEntryController.getModel().getQuestionPrompt();
    IAnswerData currentAnswer = currentQuestionPrompt.getAnswerValue();
    if (currentAnswer == null) return;

    final int dataType = currentQuestionPrompt.getDataType();
    QuestionDef questionDef = currentQuestionPrompt.getQuestion();
    String answerAsString = getMartusAnswerStringFromQuestion(currentAnswer, questionDef, dataType);
    gridRow.setCellText(columnIndex, answerAsString);
  }
  public BearingWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);

    setOrientation(LinearLayout.VERTICAL);

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

    mGetBearingButton = new Button(getContext());
    mGetBearingButton.setId(QuestionWidget.newUniqueId());
    mGetBearingButton.setPadding(20, 20, 20, 20);
    mGetBearingButton.setText(getContext().getString(R.string.get_bearing));
    mGetBearingButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mGetBearingButton.setEnabled(!prompt.isReadOnly());
    mGetBearingButton.setLayoutParams(params);
    if (prompt.isReadOnly()) {
      mGetBearingButton.setVisibility(View.GONE);
    }

    mStringAnswer = new TextView(getContext());
    mStringAnswer.setId(QuestionWidget.newUniqueId());

    mAnswerDisplay = new TextView(getContext());
    mAnswerDisplay.setId(QuestionWidget.newUniqueId());
    mAnswerDisplay.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mAnswerDisplay.setGravity(Gravity.CENTER);

    String s = prompt.getAnswerText();
    if (s != null && !s.equals("")) {
      mGetBearingButton.setText(getContext().getString(R.string.replace_bearing));
      setBinaryData(s);
    }

    // when you press the button
    mGetBearingButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Collect.getInstance()
                .getActivityLogger()
                .logInstanceAction(this, "recordBearing", "click", mPrompt.getIndex());
            Intent i = null;
            i = new Intent(getContext(), BearingActivity.class);

            Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
            ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.BEARING_CAPTURE);
          }
        });

    addView(mGetBearingButton);
    addView(mAnswerDisplay);
  }
Пример #5
0
  public TriggerWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);
    mPrompt = prompt;

    this.setOrientation(LinearLayout.VERTICAL);

    mTriggerButton = new CheckBox(getContext());
    mTriggerButton.setId(QuestionWidget.newUniqueId());
    mTriggerButton.setText(getContext().getString(R.string.trigger));
    mTriggerButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    // mActionButton.setPadding(20, 20, 20, 20);
    mTriggerButton.setEnabled(!prompt.isReadOnly());

    mTriggerButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (mTriggerButton.isChecked()) {
              mStringAnswer.setText(mOK);
              Collect.getInstance()
                  .getActivityLogger()
                  .logInstanceAction(TriggerWidget.this, "triggerButton", "OK", mPrompt.getIndex());
            } else {
              mStringAnswer.setText(null);
              Collect.getInstance()
                  .getActivityLogger()
                  .logInstanceAction(
                      TriggerWidget.this, "triggerButton", "null", mPrompt.getIndex());
            }
          }
        });

    mStringAnswer = new TextView(getContext());
    mStringAnswer.setId(QuestionWidget.newUniqueId());
    mStringAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mStringAnswer.setGravity(Gravity.CENTER);

    String s = prompt.getAnswerText();
    if (s != null) {
      if (s.equals(mOK)) {
        mTriggerButton.setChecked(true);
      } else {
        mTriggerButton.setChecked(false);
      }
      mStringAnswer.setText(s);
    }

    // finish complex layout
    this.addView(mTriggerButton);
    // this.addView(mStringAnswer);
  }
Пример #6
0
  public UrlWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);
    setOrientation(LinearLayout.VERTICAL);

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

    // set button formatting
    mOpenUrlButton = new Button(getContext());
    mOpenUrlButton.setId(QuestionWidget.newUniqueId());
    mOpenUrlButton.setText(getContext().getString(R.string.open_url));
    mOpenUrlButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mOpenUrlButton.setPadding(20, 20, 20, 20);
    mOpenUrlButton.setEnabled(!prompt.isReadOnly());
    mOpenUrlButton.setLayoutParams(params);

    mOpenUrlButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Collect.getInstance()
                .getActivityLogger()
                .logInstanceAction(this, "openUrl", "click", mPrompt.getIndex());

            if (mStringAnswer != null & mStringAnswer.getText() != null
                && !"".equalsIgnoreCase((String) mStringAnswer.getText())) {
              Intent i = new Intent(Intent.ACTION_VIEW);
              i.setData(Uri.parse((String) mStringAnswer.getText()));
              getContext().startActivity(i);
            } else {
              Toast.makeText(getContext(), "No URL set", Toast.LENGTH_SHORT).show();
            }
          }
        });

    // set text formatting
    mStringAnswer = new TextView(getContext());
    mStringAnswer.setId(QuestionWidget.newUniqueId());
    mStringAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mStringAnswer.setGravity(Gravity.CENTER);

    String s = prompt.getAnswerText();
    if (s != null) {
      mStringAnswer.setText(s);
    }
    // finish complex layout
    addView(mOpenUrlButton);
    addView(mStringAnswer);
  }
  private FormEntryPrompt findQuestion(
      FormEntryController formEntryContorller, TreeReference treeReferenceToMatch) {
    formEntryContorller.jumpToIndex(FormIndex.createBeginningOfFormIndex());
    int event;
    while ((event = formEntryContorller.stepToNextEvent())
        != FormEntryController.EVENT_END_OF_FORM) {
      if (event == FormEntryController.EVENT_QUESTION) {
        FormEntryPrompt questionPrompt = formEntryContorller.getModel().getQuestionPrompt();
        QuestionDef thisQuestionDef = questionPrompt.getQuestion();
        TreeReference thisTreeReference = (TreeReference) thisQuestionDef.getBind().getReference();
        if (thisTreeReference.equals(treeReferenceToMatch)) return questionPrompt;
      }
    }

    return null;
  }
Пример #8
0
  public IntegerWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt, true);

    mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);

    // needed to make long readonly text scroll
    mAnswer.setHorizontallyScrolling(false);
    mAnswer.setSingleLine(false);

    // only allows numbers and no periods
    mAnswer.setKeyListener(new DigitsKeyListener(true, false));

    // ints can only hold 2,147,483,648. we allow 999,999,999
    InputFilter[] fa = new InputFilter[1];
    fa[0] = new InputFilter.LengthFilter(9);
    mAnswer.setFilters(fa);

    if (prompt.isReadOnly()) {
      setBackgroundDrawable(null);
      setFocusable(false);
      setClickable(false);
    }

    Integer i = getIntegerAnswerValue();

    if (i != null) {
      mAnswer.setText(i.toString());
    }

    setupChangeListener();
  }
 protected IAnswerData getCurrentAnswer() {
   IAnswerData current = mPrompt.getAnswerValue();
   if (current == null) {
     return null;
   }
   return getTemplate().cast(current.uncast());
 }
  /**
   * Build MediuaLayout for displaying any help associated with given FormEntryPrompt.
   *
   * @param prompt
   * @return
   */
  private MediaLayout createHelpLayout(FormEntryPrompt prompt) {
    TextView text = new TextView(getContext());
    text.setText(prompt.getHelpText());
    text.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
    text.setPadding(0, 0, 0, 7);
    text.setId(38475483); // assign random id

    MediaLayout helpLayout = new MediaLayout(getContext());
    helpLayout.setAVT(
        text,
        prompt.getHelpMultimedia(FormEntryCaption.TEXT_FORM_AUDIO),
        prompt.getHelpMultimedia(FormEntryCaption.TEXT_FORM_IMAGE),
        prompt.getHelpMultimedia(FormEntryCaption.TEXT_FORM_VIDEO),
        null);
    helpLayout.setPadding(15, 15, 15, 15);

    return helpLayout;
  }
  private Bulletin createBulletin(
      MartusCrypto signatureGenerator,
      FormEntryController formEntryController,
      FieldSpecCollection fieldsFromXForms)
      throws Exception {
    FieldSpecCollection allFields = new FieldSpecCollection();
    FieldSpecCollection nonEmptytopSectionFieldSpecsFrom = getNonEmptyTopFieldSpecs();
    allFields.addAll(nonEmptytopSectionFieldSpecsFrom);
    allFields.addAll(fieldsFromXForms);

    Bulletin bulletinLoadedFromXForms =
        new Bulletin(signatureGenerator, allFields, new FieldSpecCollection());
    transferAllStandardFields(bulletinLoadedFromXForms, nonEmptytopSectionFieldSpecsFrom);

    resetFormEntryControllerIndex(formEntryController);
    int event;
    while ((event = formEntryController.stepToNextEvent())
        != FormEntryController.EVENT_END_OF_FORM) {
      if (event == FormEntryController.EVENT_REPEAT)
        convertXFormRepeatToGridData(
            formEntryController, fieldsFromXForms, bulletinLoadedFromXForms);

      if (event != FormEntryController.EVENT_QUESTION) continue;

      FormEntryPrompt questionPrompt = formEntryController.getModel().getQuestionPrompt();
      IAnswerData answer = questionPrompt.getAnswerValue();
      if (answer == null) continue;

      QuestionDef question = questionPrompt.getQuestion();
      final int dataType = questionPrompt.getDataType();
      TreeReference reference = (TreeReference) question.getBind().getReference();
      FieldDataPacket fieldDataPacket = bulletinLoadedFromXForms.getFieldDataPacket();
      String xFormsFieldTag = reference.getNameLast();
      String answerAsString = getMartusAnswerStringFromQuestion(answer, question, dataType);
      fieldDataPacket.set(xFormsFieldTag, answerAsString);
    }

    copyPrivateAttachmentProxies(bulletinLoadedFromXForms);
    copyPublicAttachmentProxies(bulletinLoadedFromXForms);

    return bulletinLoadedFromXForms;
  }
Пример #12
0
 public void refreshWidget(FormEntryPrompt fep, int changeFlags) {
   ImageItem newImItem = ExpandedWidget.getImageItem(fep, scrHeight - 16, scrWidth - 16);
   if (newImItem != null) {
     detachImage();
     fullPrompt.add(newImItem);
     imItem = newImItem;
   }
   if (multimediaController != null) {
     multimediaController.playAudioOnLoad(fep);
   }
   prompt.setText(fep.getLongText());
 }
  /**
   * Add a Views containing the question text, audio (if applicable), and image (if applicable). To
   * satisfy the RelativeLayout constraints, we add the audio first if it exists, then the TextView
   * to fit the rest of the space, then the image if applicable.
   */
  protected void addQuestionText(FormEntryPrompt p) {
    String imageURI = p.getImageText();
    String audioURI = p.getAudioText();
    String videoURI = p.getSpecialFormQuestionText("video");

    // shown when image is clicked
    String bigImageURI = p.getSpecialFormQuestionText("big-image");

    String promptText = p.getLongText();
    // Add the text view. Textview always exists, regardless of whether there's text.
    mQuestionText = new TextView(getContext());
    mQuestionText.setText(promptText == null ? "" : promptText);
    mQuestionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
    mQuestionText.setTypeface(null, Typeface.BOLD);
    mQuestionText.setPadding(0, 0, 0, 7);
    mQuestionText.setId(QuestionWidget.newUniqueId()); // assign random id

    // Wrap to the size of the parent view
    mQuestionText.setHorizontallyScrolling(false);

    if (promptText == null || promptText.length() == 0) {
      mQuestionText.setVisibility(GONE);
    }

    // Create the layout for audio, image, text
    mediaLayout = new MediaLayout(getContext());
    mediaLayout.setAVT(p.getIndex(), "", mQuestionText, audioURI, imageURI, videoURI, bigImageURI);

    addView(mediaLayout, mLayout);
  }
  public AutoCompleteWidget(Context context, FormEntryPrompt prompt, String filterType) {
    super(context, prompt);
    mItems = prompt.getSelectChoices();
    mPrompt = prompt;

    choices = new AutoCompleteAdapter(getContext(), android.R.layout.simple_list_item_1);
    autocomplete = new AutoCompleteTextView(getContext());

    // Default to matching substring
    if (filterType != null) {
      this.filterType = filterType;
    } else {
      this.filterType = match_substring;
    }

    for (SelectChoice sc : mItems) {
      choices.add(prompt.getSelectChoiceText(sc));
    }
    choices.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);

    autocomplete.setAdapter(choices);
    autocomplete.setTextColor(Color.BLACK);
    setGravity(Gravity.LEFT);

    // Fill in answer
    String s = null;
    if (mPrompt.getAnswerValue() != null) {
      s = ((Selection) mPrompt.getAnswerValue().getValue()).getValue();
    }

    for (int i = 0; i < mItems.size(); ++i) {
      String sMatch = mItems.get(i).getValue();

      if (sMatch.equals(s)) {
        autocomplete.setText(sMatch);
      }
    }

    addView(autocomplete);
  }
  private FieldSpec convertToFieldSpec(FormEntryPrompt questionPrompt) {
    QuestionDef question = questionPrompt.getQuestion();
    final int dataType = questionPrompt.getDataType();
    TreeReference reference = (TreeReference) question.getBind().getReference();
    String tag = reference.getNameLast();
    String questionLabel = questionPrompt.getQuestion().getLabelInnerText();

    if (questionPrompt.isReadOnly())
      return FieldSpec.createCustomField(tag, questionLabel, new FieldTypeMessage());

    if (isNormalFieldType(dataType))
      return FieldSpec.createCustomField(tag, questionLabel, new FieldTypeNormal());

    if (dataType == Constants.DATATYPE_DATE)
      return FieldSpec.createCustomField(tag, questionLabel, new FieldTypeDate());

    if (shouldTreatSingleItemChoiceListAsBooleanField(dataType, question))
      return FieldSpec.createCustomField(tag, questionLabel, new FieldTypeBoolean());

    if (dataType == Constants.DATATYPE_CHOICE) {
      Vector<ChoiceItem> convertedChoices = new Vector<ChoiceItem>();
      List<SelectChoice> choicesToConvert = question.getChoices();
      for (SelectChoice choiceToConvert : choicesToConvert) {
        // String choiceItemCode = choiceToConvert.getValue();
        String choiceItemLabel = choiceToConvert.getLabelInnerText();
        // Martus doesn't keep Code's when exporting so use Label twice instead
        convertedChoices.add(new ChoiceItem(choiceItemLabel, choiceItemLabel));
      }

      FieldSpec fieldSpec = new CustomDropDownFieldSpec(convertedChoices);
      fieldSpec.setTag(tag);
      fieldSpec.setLabel(questionLabel);
      return fieldSpec;
    }
    MartusLogger.log(
        "Warning: BulletinFromXFormsLoader.convertToFieldSpec unknown Field Type:"
            + String.valueOf(dataType));
    return null;
  }
Пример #16
0
  public DecimalWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);

    // formatting
    mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);

    // needed to make long readonly text scroll
    mAnswer.setHorizontallyScrolling(false);
    mAnswer.setSingleLine(false);

    // only numbers are allowed
    mAnswer.setKeyListener(new DigitsKeyListener(true, true));

    // only 15 characters allowed
    InputFilter[] fa = new InputFilter[1];
    fa[0] = new InputFilter.LengthFilter(15);
    mAnswer.setFilters(fa);

    // in case xforms calcuate returns a double, convert to integer
    Double d = null;
    if (prompt.getAnswerValue() != null) d = (Double) prompt.getAnswerValue().getValue();

    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(15);
    nf.setMaximumIntegerDigits(15);
    nf.setGroupingUsed(false);
    if (d != null) {
      mAnswer.setText(nf.format(d));
    }

    // disable if read only
    if (prompt.isReadOnly()) {
      setBackgroundDrawable(null);
      setFocusable(false);
      setClickable(false);
    }
  }
  /** Add a TextView containing the hint text. */
  private void addHintText(FormEntryPrompt p) {

    String s = p.getHintText();

    if (s != null && !s.equals("")) {
      mHintText = new ShrinkingTextView(getContext(), this.getMaxHintHeight());
      mHintText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize - 3);
      mHintText.setPadding(0, -5, 0, 7);
      // wrap to the widget of view
      mHintText.setHorizontallyScrolling(false);
      mHintText.setText(s);
      mHintText.setTypeface(null, Typeface.ITALIC);

      addView(mHintText, mLayout);
    }
  }
  /**
   * Add a Views containing the question text, audio (if applicable), and image (if applicable). To
   * satisfy the RelativeLayout constraints, we add the audio first if it exists, then the TextView
   * to fit the rest of the space, then the image if applicable.
   */
  protected void addQuestionText(final FormEntryPrompt p) {
    String imageURI = p.getImageText();
    String audioURI = p.getAudioText();
    String videoURI = p.getSpecialFormQuestionText("video");
    String qrCodeContent = p.getSpecialFormQuestionText("qrcode");

    // shown when image is clicked
    String bigImageURI = p.getSpecialFormQuestionText("big-image");

    // Add the text view. Textview always exists, regardless of whether there's text.
    mQuestionText = new TextView(getContext());
    mQuestionText.setText(p.getLongText());
    mQuestionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
    mQuestionText.setTypeface(null, Typeface.BOLD);
    mQuestionText.setPadding(0, 0, 0, 7);
    mQuestionText.setId(38475483); // assign random id

    if (p.getLongText() != null) {
      if (p.getLongText().contains("\u260E")) {
        if (Linkify.addLinks(mQuestionText, Linkify.PHONE_NUMBERS)) {
          stripUnderlines(mQuestionText);
        } else {
          System.out.println("this should be an error I'm thinking?");
        }
      }
    }
    // Wrap to the size of the parent view
    mQuestionText.setHorizontallyScrolling(false);

    if (p.getLongText() == null) {
      mQuestionText.setVisibility(GONE);
    }

    // Create the layout for audio, image, text
    MediaLayout mediaLayout = new MediaLayout(getContext());
    mediaLayout.setAVT(mQuestionText, audioURI, imageURI, videoURI, bigImageURI, qrCodeContent);
    addView(mediaLayout, mLayout);
  }
  public ExPrinterWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);

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

    String appearance = prompt.getAppearanceHint();
    String[] attrs = appearance.split(":");
    final String intentName =
        (attrs.length < 2 || attrs[1].length() == 0)
            ? "org.opendatakit.sensors.ZebraPrinter"
            : attrs[1];
    final String buttonText;
    final String errorString;
    String v = mPrompt.getSpecialFormQuestionText("buttonText");
    buttonText = (v != null) ? v : context.getString(R.string.launch_printer);
    v = mPrompt.getSpecialFormQuestionText("noPrinterErrorString");
    errorString = (v != null) ? v : context.getString(R.string.no_printer);

    // set button formatting
    mLaunchIntentButton = new Button(getContext());
    mLaunchIntentButton.setId(QuestionWidget.newUniqueId());
    mLaunchIntentButton.setText(buttonText);
    mLaunchIntentButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mLaunchIntentButton.setPadding(20, 20, 20, 20);
    mLaunchIntentButton.setLayoutParams(params);

    mLaunchIntentButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            try {
              Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
              firePrintingActivity(intentName);
            } catch (ActivityNotFoundException e) {
              Collect.getInstance().getFormController().setIndexWaitingForData(null);
              Toast.makeText(getContext(), errorString, Toast.LENGTH_SHORT).show();
            }
          }
        });

    // finish complex layout
    addView(mLaunchIntentButton);
  }
  public DecimalWidget(Context context, FormEntryPrompt prompt, boolean readOnlyOverride) {
    super(context, prompt, readOnlyOverride, true);

    // formatting
    mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);

    // needed to make long readonly text scroll
    mAnswer.setHorizontallyScrolling(false);
    mAnswer.setSingleLine(false);

    // only numbers are allowed
    mAnswer.setKeyListener(new DigitsKeyListener(true, true));

    // only 15 characters allowed
    InputFilter[] fa = new InputFilter[1];
    fa[0] = new InputFilter.LengthFilter(15);
    mAnswer.setFilters(fa);

    Double d = getDoubleAnswerValue();

    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(15);
    nf.setMaximumIntegerDigits(15);
    nf.setGroupingUsed(false);
    if (d != null) {
      // truncate to 15 digits max...
      String dString = nf.format(d);
      d = Double.parseDouble(dString.replace(',', '.'));
      mAnswer.setText(d.toString());
    }

    // disable if read only
    if (prompt.isReadOnly()) {
      setBackgroundDrawable(null);
      setFocusable(false);
      setClickable(false);
    }

    setupChangeListener();
  }
  /**
   * Display extra help, triggered by user request.
   *
   * @param prompt
   */
  private void fireHelpText(FormEntryPrompt prompt) {
    if (!prompt.hasHelp()) {
      return;
    }

    // Depending on ODK setting, help may be displayed either as
    // a dialog or inline, underneath the question text
    if (!PreferenceManager.getDefaultSharedPreferences(this.getContext().getApplicationContext())
        .getBoolean(PreferencesActivity.KEY_HELP_MODE_TRAY, false)) {
      AlertDialog mAlertDialog = new AlertDialog.Builder(this.getContext()).create();
      mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
      mAlertDialog.setTitle("");

      ScrollView scrollView = new ScrollView(this.getContext());
      scrollView.addView(createHelpLayout(prompt));
      mAlertDialog.setView(scrollView);

      DialogInterface.OnClickListener errorListener =
          new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
              switch (i) {
                case DialogInterface.BUTTON1:
                  dialog.cancel();
                  break;
              }
            }
          };
      mAlertDialog.setCancelable(true);
      mAlertDialog.setButton(
          StringUtils.getStringRobust(this.getContext(), R.string.ok), errorListener);
      mAlertDialog.show();
    } else {
      if (helpPlaceholder.getVisibility() == View.GONE) {
        expand(helpPlaceholder);
      } else {
        collapse(helpPlaceholder);
      }
    }
  }
  private void addHelpPlaceholder(FormEntryPrompt p) {
    if (!p.hasHelp()) {
      return;
    }

    helpPlaceholder = new FrameLayout(this.getContext());
    helpPlaceholder.setLayoutParams(
        new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT));

    ImageButton trigger = new ImageButton(getContext());
    trigger.setImageResource(android.R.drawable.ic_menu_help);
    final FormEntryPrompt prompt = p;
    trigger.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            fireHelpText(prompt);
          }
        });
    trigger.setId(847294011);
    LinearLayout triggerLayout = new LinearLayout(getContext());
    triggerLayout.setOrientation(LinearLayout.HORIZONTAL);
    triggerLayout.setLayoutParams(
        new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    triggerLayout.setGravity(Gravity.RIGHT);
    triggerLayout.addView(trigger);

    MediaLayout helpLayout = createHelpLayout(p);
    helpLayout.setBackgroundResource(color.very_light_blue);
    helpPlaceholder.addView(helpLayout);

    this.addView(triggerLayout);
    this.addView(helpPlaceholder);
    helpPlaceholder.setVisibility(View.GONE);
  }
    @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);
    }
  }
  public SelectOneAutoAdvanceWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);

    LayoutInflater inflater = LayoutInflater.from(getContext());

    // SurveyCTO-added support for dynamic select content (from .csv files)
    XPathFuncExpr xPathFuncExpr =
        ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
    if (xPathFuncExpr != null) {
      mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
    } else {
      mItems = prompt.getSelectChoices();
    }

    buttons = new ArrayList<RadioButton>();
    listener = (AdvanceToNextListener) context;

    String s = null;
    if (prompt.getAnswerValue() != null) {
      s = ((Selection) prompt.getAnswerValue().getValue()).getValue();
    }

    // use this for recycle
    Bitmap b =
        BitmapFactory.decodeResource(getContext().getResources(), R.drawable.expander_ic_right);

    if (mItems != null) {
      for (int i = 0; i < mItems.size(); i++) {

        RelativeLayout thisParentLayout =
            (RelativeLayout) inflater.inflate(R.layout.quick_select_layout, null);

        LinearLayout questionLayout = (LinearLayout) thisParentLayout.getChildAt(0);
        ImageView rightArrow = (ImageView) thisParentLayout.getChildAt(1);

        RadioButton r = new RadioButton(getContext());
        r.setText(prompt.getSelectChoiceText(mItems.get(i)));
        r.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
        r.setTag(Integer.valueOf(i));
        r.setId(QuestionWidget.newUniqueId());
        r.setEnabled(!prompt.isReadOnly());
        r.setFocusable(!prompt.isReadOnly());

        rightArrow.setImageBitmap(b);

        buttons.add(r);

        if (mItems.get(i).getValue().equals(s)) {
          r.setChecked(true);
        }

        r.setOnCheckedChangeListener(this);

        String audioURI = null;
        audioURI =
            prompt.getSpecialFormSelectChoiceText(mItems.get(i), FormEntryCaption.TEXT_FORM_AUDIO);

        String imageURI;
        if (mItems.get(i) instanceof ExternalSelectChoice) {
          imageURI = ((ExternalSelectChoice) mItems.get(i)).getImage();
        } else {
          imageURI =
              prompt.getSpecialFormSelectChoiceText(
                  mItems.get(i), FormEntryCaption.TEXT_FORM_IMAGE);
        }

        String videoURI = null;
        videoURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "video");

        String bigImageURI = null;
        bigImageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "big-image");

        MediaLayout mediaLayout = new MediaLayout(getContext());
        mediaLayout.setAVT(prompt.getIndex(), "", r, audioURI, imageURI, videoURI, bigImageURI);

        if (i != mItems.size() - 1) {
          // Last, add the dividing line (except for the last element)
          ImageView divider = new ImageView(getContext());
          divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
          mediaLayout.addDivider(divider);
        }
        questionLayout.addView(mediaLayout);
        addView(thisParentLayout);
      }
    }
  }
 public FormIndex getFormId() {
   return mPrompt.getIndex();
 }
 protected IAnswerData getTemplate() {
   return AnswerDataFactory.template(mPrompt.getControlType(), mPrompt.getDataType());
 }
  public SelectOneWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);

    // SurveyCTO-added support for dynamic select content (from .csv files)
    XPathFuncExpr xPathFuncExpr =
        ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
    if (xPathFuncExpr != null) {
      mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
    } else {
      mItems = prompt.getSelectChoices();
    }
    buttons = new ArrayList<RadioButton>();

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

    String s = null;
    if (prompt.getAnswerValue() != null) {
      s = ((Selection) prompt.getAnswerValue().getValue()).getValue();
    }

    if (mItems != null) {
      for (int i = 0; i < mItems.size(); i++) {
        RadioButton r = new RadioButton(getContext());
        r.setText(prompt.getSelectChoiceText(mItems.get(i)));
        r.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
        r.setTag(Integer.valueOf(i));
        r.setId(QuestionWidget.newUniqueId());
        r.setEnabled(!prompt.isReadOnly());
        r.setFocusable(!prompt.isReadOnly());

        buttons.add(r);

        if (mItems.get(i).getValue().equals(s)) {
          r.setChecked(true);
        }

        r.setOnCheckedChangeListener(this);

        String audioURI = null;
        audioURI =
            prompt.getSpecialFormSelectChoiceText(mItems.get(i), FormEntryCaption.TEXT_FORM_AUDIO);

        String imageURI;
        if (mItems.get(i) instanceof ExternalSelectChoice) {
          imageURI = ((ExternalSelectChoice) mItems.get(i)).getImage();
        } else {
          imageURI =
              prompt.getSpecialFormSelectChoiceText(
                  mItems.get(i), FormEntryCaption.TEXT_FORM_IMAGE);
        }

        String videoURI = null;
        videoURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "video");

        String bigImageURI = null;
        bigImageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "big-image");

        MediaLayout mediaLayout = new MediaLayout(getContext());
        mediaLayout.setAVT(
            prompt.getIndex(),
            "." + Integer.toString(i),
            r,
            audioURI,
            imageURI,
            videoURI,
            bigImageURI);

        if (i != mItems.size() - 1) {
          // Last, add the dividing line (except for the last element)
          ImageView divider = new ImageView(getContext());
          divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
          mediaLayout.addDivider(divider);
        }
        buttonLayout.addView(mediaLayout);
      }
    }
    buttonLayout.setOrientation(LinearLayout.VERTICAL);

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

    addView(buttonLayout, buttonParams);
  }
Пример #29
0
  public SignatureWidget(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 Blank Image Button
    mSignButton = new Button(getContext());
    mSignButton.setId(QuestionWidget.newUniqueId());
    mSignButton.setText(getContext().getString(R.string.sign_button));
    mSignButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mSignButton.setPadding(20, 20, 20, 20);
    mSignButton.setEnabled(!prompt.isReadOnly());
    mSignButton.setLayoutParams(params);
    // launch capture intent on click
    mSignButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Collect.getInstance()
                .getActivityLogger()
                .logInstanceAction(this, "signButton", "click", mPrompt.getIndex());
            launchSignatureActivity();
          }
        });

    // finish complex layout
    addView(mSignButton);
    addView(mErrorTextView);

    // and hide the sign button if read-only
    if (prompt.isReadOnly()) {
      mSignButton.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 signed
    if (mBinaryName != null) {
      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());
              launchSignatureActivity();
            }
          });

      addView(mImageView);
    }
  }
Пример #30
0
    public LabelWidget(Context context, FormEntryPrompt prompt) {
        super(context, prompt);

        mItems = prompt.getSelectChoices();
        mPrompt = prompt;

        buttonLayout = new LinearLayout(context);

        if (prompt.getSelectChoices() != null) {
            for (int i = 0; i < mItems.size(); i++) {

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

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

                // 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(23423534);
                            } 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(234873453);
                        }
                    } 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
                label = new TextView(getContext());
                label.setText(prompt.getSelectChoiceText(mItems.get(i)));
                label.setTextSize(TypedValue.COMPLEX_UNIT_DIP, TEXTSIZE);

                // answer layout holds the label text/image on top and the radio button on bottom
                LinearLayout answer = new LinearLayout(getContext());
                answer.setOrientation(LinearLayout.VERTICAL);
                LinearLayout.LayoutParams params =
                    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                            LayoutParams.WRAP_CONTENT);
                params.gravity = Gravity.TOP;
                answer.setLayoutParams(params);

                if (mImageView != null) {
                    answer.addView(mImageView);
                } else if (mMissingImage != null) {
                    answer.addView(mMissingImage);
                } else {
                    answer.addView(label);
                }
                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.FILL_PARENT, 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);

    }