@Override
  protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    if (requestCode == REQUEST_CODE_PHOTO) {
      if (resultCode == RESULT_OK) {
        if (imageReturnedIntent == null) {
        } else {

          Bundle bndl = imageReturnedIntent.getExtras();
          if (bndl != null) {
            Object obj = imageReturnedIntent.getExtras().get("data");
            if (obj instanceof Bitmap) {
              Bitmap bitmap = (Bitmap) obj;
              imbutton.setImageBitmap(bitmap);
            }
          }
        }
      } else if (resultCode == RESULT_CANCELED) {

      }
    }
    Bitmap bitmap = null;
    switch (requestCode) {
      case GALLERY_REQUEST:
        if (resultCode == RESULT_OK) {
          Uri selectedImage = imageReturnedIntent.getData();
          imbutton.setImageURI(selectedImage);
          imbutton.setImageBitmap(bitmap);
        }
    }
  }
  /**
   * The system calls this to perform work in the UI thread and delivers the result from
   * doInBackground()
   */
  protected void onPostExecute(final Article result) {
    // Preserve aspect ratio of image
    i.setScaleType(ImageView.ScaleType.CENTER_CROP);
    i.setCropToPadding(true);

    // Set downloaded bitmap
    i.setImageBitmap(result.getBitmap());

    // When clicked, should open webview to article
    i.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Intent articlePageIntent =
                new Intent(mCWrapper, ArticleActivity.class)
                    .putExtra(Intent.EXTRA_HTML_TEXT, result.getLink())
                    .putExtra(Intent.EXTRA_SHORTCUT_NAME, result.getTitle());
            mFragment.startActivity(articlePageIntent);
          }
        });

    // Title
    textView.setText(result.getTitle());

    // Remove loading bar
    progressBar.setVisibility(ProgressBar.GONE);

    // Make title visible
    textView.setVisibility(TextView.VISIBLE);

    // Save new data to HeadlineFragment
    mFragment.setArticle(result);
  }
Esempio n. 3
0
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    final View view = (View) inflater.inflate(R.layout.dialog_tox_id, null);
    builder.setView(view);
    builder.setNeutralButton(
        getString(R.string.button_ok),
        new Dialog.OnClickListener() {
          public void onClick(DialogInterface dialogInterface, int ID) {
            mListener.onDialogClick(DialogToxID.this);
          }
        });

    /* Generate or load QR image of Tox ID */
    File file = new File(Environment.getExternalStorageDirectory().getPath() + "/Antox/");
    if (!file.exists()) {
      file.mkdirs();
    }

    File noMedia =
        new File(Environment.getExternalStorageDirectory().getPath() + "/Antox/", ".nomedia");
    if (!noMedia.exists()) {
      try {
        noMedia.createNewFile();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    file = new File(Environment.getExternalStorageDirectory().getPath() + "/Antox/userkey_qr.png");
    SharedPreferences pref =
        PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
    generateQR(pref.getString("tox_id", ""));
    Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());

    ImageButton qrCode = (ImageButton) view.findViewById(R.id.qr_image);
    qrCode.setImageBitmap(bmp);
    qrCode.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(
                Intent.EXTRA_STREAM,
                Uri.fromFile(
                    new File(
                        Environment.getExternalStorageDirectory().getPath()
                            + "/Antox/userkey_qr.png")));
            shareIntent.setType("image/jpeg");
            view.getContext()
                .startActivity(
                    Intent.createChooser(
                        shareIntent, getResources().getString(R.string.share_with)));
          }
        });

    return builder.create();
  }
Esempio n. 4
0
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // To Do
    if (requestCode == 0) {
      if (resultCode == RESULT_OK) {
        Bitmap bm = (Bitmap) data.getExtras().getParcelable("data");
        // imageButton.setImageBitmap(bm);
        // textView.setText("Photo OK");

        // Save picture
        String imagepath = Environment.getExternalStorageDirectory().getAbsolutePath();
        URI uri = new URI(Environment.getExternalStorageDirectory().getAbsolutePath());
        Intent intent = new Intent(MediaStore.EXTRA_OUTPUT, uri);

        // Get screen dimensions
        DisplayMetrics display = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(display);
        int screenWidth = display.widthPixels;
        int screenHeight = display.heightPixels;

        // Scale image
        Bitmap bm_scaled;
        Boolean filter = true;
        bm_scaled = Bitmap.createScaledBitmap(bm, screenWidth, 2 * screenHeight / 3, filter);
        imageButton.setImageBitmap(bm_scaled);
        textView.setText("Photo OK");

      } else if (resultCode == RESULT_CANCELED) {
        textView.setText("Photo Canceled");
      } else {
        textView.setText("Not sure what happened.");
      }
    }
  }
 public void onPictureUpdated() {
   if (mPicture == null) return;
   ImageButton img = (ImageButton) findViewById(R.id.profile_picture);
   img.setImageBitmap(mPicture);
   img.invalidate();
   img.requestLayout();
 }
  public void setMetaInformation(MetaDataRetriever.MetaData meta) {

    if (meta == null) {
      return;
    }

    ImageButton artwork = (ImageButton) _panelView.findViewById(R.id.image_artwork);
    if (meta.artwork != null) {
      artwork.setImageBitmap(meta.artwork);
    } else {
      artwork.setImageResource(R.drawable.ic_launcher);
    }

    TextView text = (TextView) _panelView.findViewById(R.id.text_title);
    text.setText(meta.title);

    text = (TextView) _panelView.findViewById(R.id.text_artist);
    text.setText(meta.artistName);

    text = (TextView) _panelView.findViewById(R.id.text_position);
    text.setText(TimecodeUtils.START_POSITION);

    SeekBar bar = (SeekBar) _panelView.findViewById(R.id.seekbar_position);
    bar.setMax((int) meta.duration);
    bar.setProgress(0);

    text = (TextView) _panelView.findViewById(R.id.text_duration);
    text.setText(TimecodeUtils.format(meta.duration));
  }
  // Filling the data for the edit contact
  public void fillDataForEdit() {
    // Add columns to read to an array
    String columns[] =
        new String[] {
          ABProviderContract._ID,
          ABProviderContract.NAME,
          ABProviderContract.MOBILE_NUMBER,
          ABProviderContract.HOME_NUMBER,
          ABProviderContract.WORK_NUMBER,
          ABProviderContract.EMAIL_ADDRESS,
          ABProviderContract.WEBSITE,
          ABProviderContract.IMAGE_URL
        };

    // ContactId is used to get the contact editing.
    Cursor cursor =
        getContentResolver().query(ABProviderContract.CONTACTS_URI, columns, null, null, null);
    if (cursor.moveToFirst()) {
      while (cursor.moveToNext()) {
        if (cursor.getString(0).equals(contactId)) {
          // Adding text to the edit texts using the editing contact
          edName.setText(cursor.getString(1));
          edMobileNum.setText(cursor.getString(2));
          edWorkNum.setText(cursor.getString(3));
          edHomeNum.setText(cursor.getString(4));
          edEmail.setText(cursor.getString(5));
          edWebsite.setText(cursor.getString(6));
          btnAddPhoto.setImageBitmap(BitmapFactory.decodeFile(cursor.getString(7)));
        }
      }
    }
  }
Esempio n. 8
0
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {

    Log.d(TAG, "I'm here in ImageCollector's onActivityResult");

    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {

      int iBWidth = mImageButton.getWidth();
      int iBHeight = mImageButton.getHeight();

      // First decode with inJustDecodeBounds=true to check dimensions
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(mCurrentPhotoPath, options);

      // Calculate inSampleSize
      options.inSampleSize = ImageAdapter.calculateInSampleSize(options, iBWidth, iBHeight);
      options.inJustDecodeBounds = false;

      mImageButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
      mImageButton.setImageBitmap(BitmapFactory.decodeFile(mCurrentPhotoPath, options));

      GridView imageGrid = (GridView) findViewById(R.id.image_collector_grid);
      imageGrid.setAdapter(mAdapter);
      // mAdapter.loadBitmap(mImageButton, mThumbPosition);
      // mAdapter.notifyDataSetChanged();
    } else Log.d(TAG, "Image Capture Failed or Cancelled");
  }
  private void updateFavicon(Tab tab) {
    if (HardwareUtils.isTablet()) {
      // We don't display favicons in the toolbar on tablet.
      return;
    }

    if (tab == null) {
      mFavicon.setImageDrawable(null);
      return;
    }

    Bitmap image = tab.getFavicon();

    if (image != null && image == mLastFavicon) {
      Log.d(LOGTAG, "Ignoring favicon: new image is identical to previous one.");
      return;
    }

    // Cache the original so we can debounce without scaling
    mLastFavicon = image;

    Log.d(LOGTAG, "updateFavicon(" + image + ")");

    if (image != null) {
      image = Bitmap.createScaledBitmap(image, mFaviconSize, mFaviconSize, false);
      mFavicon.setImageBitmap(image);
    } else {
      mFavicon.setImageResource(R.drawable.favicon);
    }
  }
 /** Set the contents om the Thumbnail image button */
 private void setThumbnail() {
   if (imageUri != null) {
     Bitmap thumb = getThumbnail(imageUri);
     Log.d(TAG, "setting thumbnail : " + thumb);
     if (thumb != null) {
       ibThumb.setImageBitmap(thumb);
     }
   }
 }
 // Called when the user selected an image from the photo library
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if (resultCode != RESULT_CANCELED) {
     if (requestCode == REQUEST_LIBRARY) {
       // gettting the absolute path of the image
       imageUrl = getAbsolutePath(data.getData());
       // Updating the add photo button with the image which is converted to a bitmap
       btnAddPhoto.setImageBitmap(BitmapFactory.decodeFile(imageUrl));
     }
   }
 }
Esempio n. 12
0
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (data != null) {
     if (resultCode == RESULT_OK) {
       Bitmap bm = (Bitmap) data.getExtras().getParcelable("data");
       imageButton.setImageBitmap(bm);
       textView.setText("Photo OK");
     } else if (resultCode == RESULT_CANCELED) {
       textView.setText("Photo Cancelled");
     } else {
       textView.setText("Not sure what happened");
     }
   }
 }
Esempio n. 13
0
  @Override
  public void colorChanged(int pos, int color) {
    ImageButton btn = (ImageButton) findViewById(R.id.buttonColor);

    int btnColor = 0;
    if (pos >= mApp.getDisplay().getColorCount()) btnColor = mViewBanner.getSelColor();

    Bitmap bm =
        ColorPickerAdapter.getColorBitmap(
            pos, 80, btnColor, color, mApp.getDisplay().getColorCount(), false);
    btn.setImageBitmap(Bitmap.createScaledBitmap(bm, 64, 64, true));

    Log.d(TAG, "color " + pos);
    if (mViewBanner != null) mViewBanner.setSelColor(pos, color);
  }
Esempio n. 14
0
  @Override
  public synchronized void onResume() {
    super.onResume();

    OnButtonDone(null);
    String str = mApp.getDisplay().getText();
    EditText editBanner = (EditText) findViewById(R.id.editTextBanner);
    if (editBanner != null && str != null) {
      editBanner.setText(str.toCharArray(), 0, str.length());
    }

    if (mSpinnerFont != null) {
      mSpinnerFont.setSelection(mFontSelIdx);
    }

    updateLedSignInfo(false);

    CheckBox checkVScrollLock = (CheckBox) findViewById(R.id.checkBoxVScroll);
    if (checkVScrollLock != null) {
      boolean check = mViewBanner.getVScroll();
      checkVScrollLock.setChecked(check);
    }

    int nColor = mApp.getDisplay().getDefaultColor();
    mViewBanner.setSelColor(mApp.getDisplay().getColorCount() - 1, nColor);

    int pos = mApp.getDisplay().getColorCount() - 1;
    ImageButton btn = (ImageButton) findViewById(R.id.buttonColor);
    if (btn != null) {
      Bitmap bm =
          ColorPickerAdapter.getColorBitmap(
              pos, 80, 0, nColor, mApp.getDisplay().getColorCount(), false);
      btn.setImageBitmap(Bitmap.createScaledBitmap(bm, 64, 64, true));
    }

    SeekBar speedBar = (SeekBar) findViewById(R.id.seekBarSpeed);
    if (speedBar != null) {
      speedBar.setProgress(mIntPlaySpeed);
    }

    changeSyncButtonState(mBTConnected);

    mViewBanner.invalidate();

    if (mApp.getDisplay() == null || mApp.getDisplay().getBTState() != SerialPort.STATE_CONNECTED)
      mApp.connectDev(new CNKHandler(this));
  }
Esempio n. 15
0
  private void initDisplay() {
    aspcaAlity_ = cat_.getASPCAality();

    final int color = cat_.getASPCAalityColor();

    final Bitmap bitmap = cat_.getSmPhoto();
    imagePhoto_.setImageBitmap(bitmap);
    imagePhoto_.setBackgroundColor(color);

    final ImageView imageAdopted = (ImageView) findViewById(R.id.imageAdopted);
    final int status = cat_.getStatus();
    int visibility = View.INVISIBLE;
    if (status == AppDBAdapter.STATUS_ADOPTED) {
      visibility = View.VISIBLE;
    }
    imageAdopted.setVisibility(visibility);

    final TextView textAgeSex = (TextView) findViewById(R.id.textAgeSex);
    final String age_sex = cat_.getAge() + " " + cat_.getSex();
    textAgeSex.setText(age_sex);
    textAgeSex.setBackgroundColor(color);

    final int aspcaAlityResId = cat_.getASPCAalityResID();
    textASPCAality_.setText(aspcaAlityResId);
    textASPCAality_.setBackgroundColor(color);

    final String name = cat_.getName();
    textName_.setText(name);
    textName_.setTextColor(color);

    final TextView textBio = (TextView) findViewById(R.id.textBio);

    final int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentapiVersion > android.os.Build.VERSION_CODES.DONUT) {
      textBio.setAutoLinkMask(Linkify.ALL);
    }

    final String bio_en = cat_.getBiography();
    final String bioText = Util.concatNoTranslation(this, bio_en);
    textBio.setText(bioText);

    final TextView textPetID = (TextView) findViewById(R.id.textPetID);
    final String petID = getString(R.string.pet_id) + ": " + cat_.getPetID();
    textPetID.setText(petID);
    textPetID.setBackgroundColor(color);
  }
Esempio n. 16
0
  private void getPic(Intent data) {
    if (null != data) {
      // 取出所选图片的路径
      Uri selectedImage = data.getData();
      String[] filePathColumn = {MediaStore.Images.Media.DATA};

      Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
      cursor.moveToFirst();

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
      String picuri = cursor.getString(columnIndex);
      cursor.close();

      // 将图片贴到控件上
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(picuri, options);
      int width = options.outWidth;
      int height = options.outHeight;
      if (100 > width || 40 > height) {
        // 图片分辨率太低
        Toast.makeText(this, getString(R.string.question_imagetoosmall), Toast.LENGTH_SHORT).show();
        MobclickAgent.onEvent(this, "addQP_F");
        return;
      }

      BitmapFactory.Options opts = new BitmapFactory.Options();
      opts.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(picuri, opts);
      opts.inSampleSize = computeSampleSize(opts, -1, 700 * 272);
      opts.inJustDecodeBounds = false;
      try {
        bitmap = BitmapFactory.decodeFile(picuri, opts);
      } catch (OutOfMemoryError err) {
        // showNotification("图片过大!");
        MobclickAgent.onEvent(this, "addQP_F");
        Toast.makeText(this, getString(R.string.question_imagetoolarge), Toast.LENGTH_SHORT).show();
        return;
      }
      MobclickAgent.onEvent(this, "addQP_S");
      image.setScaleType(ImageView.ScaleType.FIT_CENTER);
      image.setImageBitmap(bitmap);
      hint.setText(getString(R.string.question_removeimage_hint));
    }
  }
Esempio n. 17
0
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
      Uri selectedImage = data.getData();
      String[] filePathColumn = {MediaStore.Images.Media.DATA};

      Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
      cursor.moveToFirst();

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
      String picturePath = cursor.getString(columnIndex);
      cursor.close();

      profilePicture.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    }
  } //
Esempio n. 18
0
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);

      if (resultCode == RESULT_OK) {
        if (requestCode == PHOTO_GET) {
          Uri selectedImageUri = data.getData();

          String tempPath = getPath(selectedImageUri, userActivity);
          photoFile = tempPath;
          Bitmap bitMap;
          BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
          bitMap = BitmapFactory.decodeFile(tempPath, bitmapOptions);
          addPhotoImageButton.setImageBitmap(bitMap);
          RequestForSend.getInstance().sendMeServerForUploadPhoto();
        }
      }
    }
  private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    File destination =
        new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");

    FileOutputStream fo;
    try {
      destination.createNewFile();
      fo = new FileOutputStream(destination);
      fo.write(bytes.toByteArray());
      fo.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    imgProfileBtn.setImageBitmap(thumbnail);
  }
  @SuppressWarnings("deprecation")
  private void onSelectFromGalleryResult(Intent data) {
    Uri selectedImageUri = data.getData();
    String[] projection = {MediaColumns.DATA};
    Cursor cursor = managedQuery(selectedImageUri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();

    String selectedImagePath = cursor.getString(column_index);

    Bitmap bm;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(selectedImagePath, options);
    final int REQUIRED_SIZE = 200;
    int scale = 1;
    while (options.outWidth / scale / 2 >= REQUIRED_SIZE
        && options.outHeight / scale / 2 >= REQUIRED_SIZE) scale *= 2;
    options.inSampleSize = scale;
    options.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(selectedImagePath, options);

    imgProfileBtn.setImageBitmap(bm);
  }
Esempio n. 21
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);
    }
Esempio n. 22
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game_screen);
    gameOver = false;
    AdView mAdView = (AdView) findViewById(R.id.adView);
    vibrate = (Vibrator) getSystemService(VIBRATOR_SERVICE);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
    charButton = (ImageButton) findViewById(R.id.goodIcon);
    x = getResources().getDrawable(R.mipmap.playericon);
    charButton.setImageDrawable(x);
    SharedPreferences mypreferences =
        getSharedPreferences("App_preferences_file", Context.MODE_PRIVATE);
    soundEnabled = mypreferences.getBoolean("sound", true);
    vibrateEnabled = mypreferences.getBoolean("vibrateenabled", true);
    musicEnabled = mypreferences.getBoolean("musicenabled", true);

    if (musicEnabled) {
      mySound = MediaPlayer.create(this, R.raw.gamesound2);
      mySound.setLooping(true);
      mySound.start();
    }

    // If this got started from camera activity grab the string that was passed with it
    if (getIntent().hasExtra("image")) {
      Bundle extras = getIntent().getExtras();
      if (extras != null) {
        photo = (Bitmap) extras.get("data");
        charButton = (ImageButton) findViewById(R.id.goodIcon);
        charButton.setImageBitmap(photo);
      }
    }
    createBadTimer(timerValue);
    // sets the countdown to track lives
    lifeTimer =
        new CountDownTimer(timefactor, 1) {
          public void onTick(long millisUntilFinished) {}

          public void onFinish() {
            loseLife();
          }
        }.start();
    // TIMER FOR MOVING THE BUTTON AUTOMATICALLY
    moveTimer =
        new CountDownTimer(1260000, timefactor) {
          public void onTick(long millisUntilFinished) {
            Handler handler = new Handler();
            handler.postDelayed(
                new Runnable() {
                  public void run() {
                    moveButton();
                  }
                },
                1000);
          }

          public void onFinish() {}
        }.start();
    scoreText = (TextView) findViewById(R.id.player1score);
    Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/scoreFont.otf");
    scoreText.setTypeface(typeFace);
  }
Esempio n. 23
0
  // Draws the Events
  private void drawEvents() {

    int counter = 0;
    layout.removeAllViews();
    for (JSONObject j : events) {
      try {
        final String eid = j.getString("eid");
        final String name = j.getString("name");
        final int icon = j.getInt("icon");
        final int creator = j.getInt("creator");
        String update = j.getString("updated");
        final String temp = j.getString("datetime");
        String month = temp.substring(5, 7);
        String day = temp.substring(8, 10);
        String date = day + '-' + month;

        RelativeLayout.LayoutParams lp_icon = new RelativeLayout.LayoutParams(height, height);
        RelativeLayout.LayoutParams lp_button = new RelativeLayout.LayoutParams(width, height);
        RelativeLayout.LayoutParams lp_date = new RelativeLayout.LayoutParams(dateWidth, height);
        RelativeLayout.LayoutParams lp_div = new RelativeLayout.LayoutParams(width, divHeight);

        /**
         * Adds the icon: to limit the use of data we store the images in a local database, and in
         * an online database. Whenever someone uploads a new icon a new random icon_ID gets
         * generated when the icon_ID in your local DB doesn't equal the one in the online database,
         * the one in the online DB gets downloaded and the offline DB gets updated with this EID
         * and image.
         */
        lp_icon.setMargins(0, (height + divHeight) * counter, 0, 0);
        final ImageButton img = new ImageButton(this);
        if (icon == 0) {
          img.setImageResource(R.drawable.group);
          img.setPadding(12, 12, 12, 12);
          user_db.deleteBlob(eid);
        } else {
          if (icon == user_db.getVersion(eid)) {
            byte[] image = user_db.getBlob(eid);
            img.setImageBitmap(BitmapFactory.decodeByteArray(image, 0, image.length));
            img.setPadding(7, 7, 7, 7);
          } else {
            String tag_icon = "req_icon";
            StringRequest stringRequest =
                new StringRequest(
                    Request.Method.POST,
                    URL_ICON,
                    new Response.Listener<String>() {

                      @Override
                      public void onResponse(String response) {
                        try {
                          JSONObject jObj = new JSONObject(response);
                          boolean error = jObj.getBoolean("error");

                          if (!error) {
                            byte[] blob = Base64.decode(jObj.getString("blob"), Base64.DEFAULT);
                            if (user_db.getVersion(eid) == 0) {
                              user_db.addBLOB(eid, icon, blob);
                            } else {
                              user_db.updateBlob(eid, icon, blob);
                            }
                            img.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0, blob.length));
                            img.setPadding(7, 7, 7, 7);
                          }
                        } catch (JSONException e) {
                          e.printStackTrace();
                        }
                      }
                    },
                    new Response.ErrorListener() {

                      @Override
                      public void onErrorResponse(VolleyError error) {}
                    }) {

                  @Override
                  protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("tag", "get");
                    params.put("eid", eid);
                    return params;
                  }
                };
            AppController.getInstance().addToRequestQueue(stringRequest, tag_icon);
          }
        }
        img.setLayoutParams(lp_icon);
        img.setBackground(null);
        img.setScaleType(ImageView.ScaleType.FIT_CENTER);
        layout.addView(img);

        // Add the button
        lp_button.setMargins(height, (height + divHeight) * counter, height, 0);
        TextView button = new TextView(this);
        button.setText(name);
        button.setTypeface(express);
        button.setTextSize(getResources().getDimension(R.dimen.button_text));
        button.setTextColor(getResources().getColor(R.color.black));
        button.setGravity(Gravity.CENTER_VERTICAL);
        button.setLayoutParams(lp_button);
        layout.addView(button);
        button.setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, EventActivity.class);
                Bundle b = new Bundle();
                b.putString("eid", eid);
                b.putString("name", name);
                b.putInt("icon", icon);
                b.putInt("creator", creator);
                b.putString("date", temp);
                intent.putExtras(b);
                startActivity(intent);
              }
            });

        // Add the Date
        if (!month.equals("00") && !day.equals("00")) {
          lp_date.setMargins(0, (height + divHeight) * counter, 0, 0);
          lp_date.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
          TextView datetime = new TextView(this);
          datetime.setText(date);
          datetime.setGravity(Gravity.CENTER);
          datetime.setLayoutParams(lp_date);
          layout.addView(datetime);
        }

        // Add the Divider
        lp_div.setMargins(height, (height + divHeight) * counter + height, 20, 0);
        ImageView div = new ImageView(this);
        div.setImageResource(R.drawable.divider);
        div.setLayoutParams(lp_div);
        layout.addView(div);

        counter++;
      } catch (JSONException ex) {

      }
    }
  }
Esempio n. 24
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_friend_profile);

    friendKey = getIntent().getStringExtra("key");
    friendGroup = getIntent().getStringExtra("group");
    AntoxDB db = new AntoxDB(this);
    String[] friendDetails = db.getFriendDetails(friendKey);
    friendName = friendDetails[0];
    String friendAlias = friendDetails[1];
    String friendNote = friendDetails[2];

    setTitle(friendName + "'s Profile");

    EditText editFriendAlias = (EditText) findViewById(R.id.friendAliasText);
    editFriendAlias.setText(friendAlias);

    TextView editFriendNote = (TextView) findViewById(R.id.friendNoteText);
    editFriendNote.setText("\"" + friendNote + "\"");

    TextView editFriendKey = (TextView) findViewById(R.id.friendKeyText);
    editFriendKey.setText(friendKey);

    // set the spinner
    Spinner friendGroupSpinner = (Spinner) findViewById(R.id.spinner_friend_profile_group);
    ArrayList<String> spinnerArray = new ArrayList<String>();
    spinnerArray.add(getResources().getString(R.string.manage_groups_friends));
    SharedPreferences sharedPreferences = getSharedPreferences("groups", Context.MODE_PRIVATE);
    int position = 0;
    if (!sharedPreferences.getAll().isEmpty()) {
      Map<String, ?> keys = sharedPreferences.getAll();

      for (Map.Entry<String, ?> entry : keys.entrySet()) {
        String groupName = entry.getValue().toString();
        spinnerArray.add(groupName);
        if (groupName.equals(friendGroup)) {
          position = spinnerArray.size() - 1;
        }
      }
    }
    ArrayAdapter<String> spinnerAdapter =
        new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinnerArray);
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    friendGroupSpinner.setAdapter(spinnerAdapter);
    friendGroupSpinner.setSelection(position);

    /* Looks for the userkey qr.png if it doesn't exist then it creates it with the generateQR method.
     * adds onClickListener to the ImageButton to add share the QR
     * */
    ImageButton qrCode = (ImageButton) findViewById(R.id.qr_code);

    File file = new File(Environment.getExternalStorageDirectory().getPath() + "/Antox/");
    if (!file.exists()) {
      file.mkdirs();
    }
    File noMedia =
        new File(Environment.getExternalStorageDirectory().getPath() + "/Antox/", ".nomedia");
    if (!noMedia.exists()) {
      try {
        noMedia.createNewFile();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    file =
        new File(
            Environment.getExternalStorageDirectory().getPath() + "/Antox/" + friendName + ".png");
    generateQR(friendKey);
    Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());
    qrCode.setImageBitmap(bmp);
    qrCode.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(
                Intent.EXTRA_STREAM,
                Uri.fromFile(
                    new File(
                        Environment.getExternalStorageDirectory().getPath()
                            + "/Antox/"
                            + friendName
                            + ".png")));
            shareIntent.setType("image/jpeg");
            startActivity(
                Intent.createChooser(shareIntent, getResources().getString(R.string.share_with)));
          }
        });

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
      getSupportActionBar().setIcon(R.drawable.ic_actionbar);
    }
  }
Esempio n. 25
0
  private void setUpInterface() {
    timerView = commentsBar.findViewById(R.id.timer_container);
    commentButton = commentsBar.findViewById(R.id.commentButton);
    commentField = (EditText) commentsBar.findViewById(R.id.commentField);

    final boolean showTimerShortcut = Preferences.getBoolean(R.string.p_show_timer_shortcut, false);

    if (showTimerShortcut) {
      commentField.setOnFocusChangeListener(
          new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
              if (hasFocus) {
                timerView.setVisibility(View.GONE);
                commentButton.setVisibility(View.VISIBLE);
              } else {
                timerView.setVisibility(View.VISIBLE);
                commentButton.setVisibility(View.GONE);
              }
            }
          });
    } else {
      timerView.setVisibility(View.GONE);
    }

    commentField.addTextChangedListener(
        new TextWatcher() {
          @Override
          public void afterTextChanged(Editable s) {
            commentButton.setVisibility(
                (s.length() > 0 || pendingCommentPicture != null) ? View.VISIBLE : View.GONE);
            if (showTimerShortcut)
              timerView.setVisibility(
                  (s.length() > 0 || pendingCommentPicture != null) ? View.GONE : View.VISIBLE);
          }

          @Override
          public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //
          }

          @Override
          public void onTextChanged(CharSequence s, int start, int before, int count) {
            //
          }
        });

    commentField.setOnEditorActionListener(
        new OnEditorActionListener() {
          @Override
          public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_NULL && commentField.getText().length() > 0) {
              addComment();
              return true;
            }
            return false;
          }
        });
    commentButton.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            addComment();
          }
        });

    final ClearImageCallback clearImage =
        new ClearImageCallback() {
          @Override
          public void clearImage() {
            pendingCommentPicture = null;
            pictureButton.setImageResource(cameraButton);
          }
        };
    pictureButton = (ImageButton) commentsBar.findViewById(R.id.picture);
    pictureButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (pendingCommentPicture != null)
              ActFmCameraModule.showPictureLauncher(fragment, clearImage);
            else ActFmCameraModule.showPictureLauncher(fragment, null);
            respondToPicture = true;
          }
        });
    if (!TextUtils.isEmpty(task.getValue(Task.NOTES))) {
      TextView notes = new TextView(getContext());
      notes.setLinkTextColor(Color.rgb(100, 160, 255));
      notes.setTextSize(18);
      notes.setText(task.getValue(Task.NOTES));
      notes.setPadding(5, 10, 5, 10);
      Linkify.addLinks(notes, Linkify.ALL);
    }

    if (activity != null) {
      Bitmap bitmap =
          activity.getIntent().getParcelableExtra(TaskEditFragment.TOKEN_PICTURE_IN_PROGRESS);
      if (bitmap != null) {
        pendingCommentPicture = bitmap;
        pictureButton.setImageBitmap(pendingCommentPicture);
      }
    }

    // TODO add loading text back in
    //        loadingText = (TextView) findViewById(R.id.loading);
    loadingText = new TextView(getContext());
  }
Esempio n. 26
0
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
      case RESULT_USERIMG:
        if (null == data) {
          ToastUtil.show(this, "未选择图片");
        } else {
          Intent intent = new Intent("com.android.camera.action.CROP");
          intent.setDataAndType(data.getData(), "image/*");
          intent.putExtra("crop", "true");
          intent.putExtra("aspectX", 1);
          intent.putExtra("aspectY", 1);
          intent.putExtra("outputX", 320);
          intent.putExtra("outputY", 320);
          intent.putExtra("return-data", true);
          startActivityForResult(intent, RESULT_USERIMGCROP);
        }
        break;

      case RESULT_USERIMGCROP:
        if (data != null) {
          Bundle extras = data.getExtras();
          if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            if (photo != null) {
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              photo.compress(Bitmap.CompressFormat.PNG, 100, baos);
              byte[] buf = baos.toByteArray();
              File file = new File(Environment.getExternalStorageDirectory(), "headdisplay");
              upTemp = file.getAbsolutePath();
              BufferedOutputStream bos = null;
              FileOutputStream fos = null;
              try {
                fos = new FileOutputStream(file);
                bos = new BufferedOutputStream(fos);
                bos.write(buf);
                userpic.setImageBitmap(photo);
              } catch (Exception e) {
                ToastUtil.show(this, "获取图片失败");
              } finally {
                if (bos != null) {
                  try {
                    bos.close();
                  } catch (IOException e) {
                  }
                }
                if (fos != null) {
                  try {
                    fos.close();
                  } catch (IOException e) {
                  }
                }
              }
            } else {
              ToastUtil.show(this, "未选择图片");
            }
          } else {
            ToastUtil.show(this, "未选择图片");
          }
        } else {
          ToastUtil.show(this, "未选择图片");
        }
        break;
    }
  }