Java Code Examples for android.support.annotation.Size

The following are top voted examples for showing how to use android.support.annotation.Size. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: LinkagePicker.java   View source code 6 votes vote down vote up
/**
 * 根据比例计算,获取每列的实际宽度。
 * 三级联动默认每列宽度为屏幕宽度的三分之一,两级联动默认每列宽度为屏幕宽度的一半。
 */
@Size(3)
protected int[] getColumnWidths(boolean onlyTwoColumn) {
    LogUtils.verbose(this, String.format(java.util.Locale.CHINA, "column weight is: %f-%f-%f"
            , firstColumnWeight, secondColumnWeight, thirdColumnWeight));
    int[] widths = new int[3];
    // fixed: 17-1-7 Equality tests should not be made with floating point values.
    if ((int) firstColumnWeight == 0 && (int) secondColumnWeight == 0
            && (int) thirdColumnWeight == 0) {
        if (onlyTwoColumn) {
            widths[0] = screenWidthPixels / 2;
            widths[1] = widths[0];
            widths[2] = 0;
        } else {
            widths[0] = screenWidthPixels / 3;
            widths[1] = widths[0];
            widths[2] = widths[0];
        }
    } else {
        widths[0] = (int) (screenWidthPixels * firstColumnWeight);
        widths[1] = (int) (screenWidthPixels * secondColumnWeight);
        widths[2] = (int) (screenWidthPixels * thirdColumnWeight);
    }
    return widths;
}
 
Example 2
Project: AndroidBackendlessChat   File: ImageUtils.java   View source code 6 votes vote down vote up
/**
 * Constructing a bitmap that contains the given bitmaps(max is three).
 *
 * For given two bitmaps the result will be a half and half bitmap.
 *
 * For given three the result will be a half of the first bitmap and the second
 * half will be shared equally by the two others.
 *
 * @param  bitmaps Array of bitmaps to use for the final image.
 * @param  width width of the final image, A positive number.
 * @param  height height of the final image, A positive number.
 *
 * @return A Bitmap containing the given images.
 * */
@Nullable public static Bitmap getMixImagesBitmap(@Size(min = 1) int width,@Size(min = 1) int height, @NonNull Bitmap...bitmaps){

    if (height == 0 || width == 0) return null;

    if (bitmaps.length == 0) return null;

    Bitmap finalImage = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(finalImage);

    Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);

    if (bitmaps.length == 2){
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[0], width/2, height), 0, 0, paint);
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[1], width/2, height), width/2, 0, paint);
    }
    else{
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[0], width/2, height), 0, 0, paint);
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[1], width/2, height/2), width/2, 0, paint);
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[2], width/2, height/2), width/2, height/2, paint);
    }

    return finalImage;
}
 
Example 3
Project: MiPushFramework   File: CondomContext.java   View source code 6 votes vote down vote up
private CondomContext(final CondomCore condom, final @Nullable Context app_context, final @Nullable @Size(max=16) String tag) {
	super(condom.mBase);
	final Context base = condom.mBase;
	mCondom = condom;
	mApplicationContext = app_context != null ? app_context : this;
	mBaseContext = new Lazy<Context>() { @Override protected Context create() {
		return new PseudoContextImpl(CondomContext.this);
	}};
	mPackageManager = new Lazy<PackageManager>() { @Override protected PackageManager create() {
		return new CondomPackageManager(base.getPackageManager());
	}};
	mContentResolver = new Lazy<ContentResolver>() { @Override protected ContentResolver create() {
		return new CondomContentResolver(base, base.getContentResolver());
	}};
	final List<CondomKit> kits = condom.mKits;
	if (kits != null && ! kits.isEmpty()) {
		mKitManager = new KitManager();
		for (final CondomKit kit : kits)
			kit.onRegister(mKitManager);
	} else mKitManager = null;
	TAG = CondomCore.buildLogTag("Condom", "Condom.", tag);
}
 
Example 4
Project: hey-permission   File: HeyPermission.java   View source code 6 votes vote down vote up
/**
 * Check if the calling context has a set of permissions.
 *
 * @param context     The calling context
 * @param permissions One or more permission.
 * @return True if all permissions are already granted, false if at least one permission is not
 * yet granted.
 * @see android.Manifest.permission
 */
public static boolean hasPermissions(@NonNull Context context,
                                     @NonNull @Size(min = 1) String... permissions) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }

    final AppOpsManager appOpsManager = context.getSystemService(AppOpsManager.class);
    final String packageName = context.getPackageName();
    for (String permission : permissions) {
        if (ContextCompat.checkSelfPermission(context, permission)
                != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        String op = AppOpsManager.permissionToOp(permission);
        if (!TextUtils.isEmpty(op) && appOpsManager != null
                && appOpsManager.noteProxyOp(op, packageName) != AppOpsManager.MODE_ALLOWED) {
            return false;
        }
    }
    return true;
}
 
Example 5
Project: hey-permission   File: HeyPermission.java   View source code 6 votes vote down vote up
private static void requestPermissions(@NonNull BasePermissionInvoker invoker,
                                       @IntRange(from = 0) int requestCode,
                                       @Size(min = 1) @NonNull String[]... permissionSets) {
    final List<String> permissionList = new ArrayList<>();
    for (String[] permissionSet : permissionSets) {
        permissionList.addAll(Arrays.asList(permissionSet));
    }
    final String[] permissions = permissionList.toArray(new String[permissionList.size()]);
    if (hasPermissions(invoker.getContext(), permissions)) {
        notifyAlreadyHasPermissions(invoker, requestCode, permissions);
        return;
    }
    if (invoker.shouldShowRequestPermissionRationale(permissions)) {
        if (invokeShowRationaleMethod(false, invoker, requestCode, permissions)) {
            return;
        }
    }
    invoker.executeRequestPermissions(requestCode, permissions);
}
 
Example 6
Project: hey-permission   File: PermissionDialogs.java   View source code 6 votes vote down vote up
public static void showDefaultRationaleDialog(
        @NonNull Context context, @NonNull final PermissionRequestExecutor executor,
        @IntRange(from = 0) final int code,
        @NonNull @Size(min = 1) final String... permissions) {
    new AlertDialog.Builder(context)
            .setTitle(R.string.hey_permission_request_title)
            .setMessage(R.string.hey_permission_request_message)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    executor.executeRequestPermissions(code, permissions);
                }
            })
            .setCancelable(false)
            .show();
}
 
Example 7
Project: chat-sdk-android-push-firebase   File: ImageUtils.java   View source code 6 votes vote down vote up
/**
 * Constructing a bitmap that contains the given bitmaps(max is three).
 *
 * For given two bitmaps the result will be a half and half bitmap.
 *
 * For given three the result will be a half of the first bitmap and the second
 * half will be shared equally by the two others.
 *
 * @param  bitmaps Array of bitmaps to use for the final image.
 * @param  width width of the final image, A positive number.
 * @param  height height of the final image, A positive number.
 *
 * @return A Bitmap containing the given images.
 * */
@Nullable public static Bitmap getMixImagesBitmap(@Size(min = 1) int width,@Size(min = 1) int height, @NonNull Bitmap...bitmaps){

    if (height == 0 || width == 0) return null;

    if (bitmaps.length == 0) return null;

    Bitmap finalImage = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(finalImage);

    Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);

    if (bitmaps.length == 2){
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[0], width/2, height), 0, 0, paint);
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[1], width/2, height), width/2, 0, paint);
    }
    else{
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[0], width/2, height), 0, 0, paint);
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[1], width/2, height/2), width/2, 0, paint);
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[2], width/2, height/2), width/2, height/2, paint);
    }

    return finalImage;
}
 
Example 8
Project: Blockly   File: AbstractBlockView.java   View source code 6 votes vote down vote up
@Override
public void getTouchLocationOnScreen(MotionEvent event, @Size(2) int[] locationOut) {
    int pointerId = event.getPointerId(event.getActionIndex());
    int pointerIdx = event.findPointerIndex(pointerId);
    float offsetX =  event.getX(pointerIdx);
    float offsetY = event.getY(pointerIdx);

    // Get local screen coordinates.
    getLocationOnScreen(locationOut);

    // add the scaled offset.
    if (mWorkspaceView != null) {
        float scale = mWorkspaceView.getScaleX();
        offsetX = offsetX * scale;
        offsetY = offsetY * scale;
    }
    locationOut[0] += (int) offsetX;
    locationOut[1] += (int) offsetY;
}
 
Example 9
Project: Blockly   File: Dragger.java   View source code 6 votes vote down vote up
/**
 * Checks whether {@code actionMove} is beyond the allowed slop (i.e., unintended) drag motion
 * distance.
 *
 * @param actionMove The {@link MotionEvent#ACTION_MOVE} event.
 * @return True if the motion is beyond the allowed slop threshold
 */
private boolean isBeyondSlopThreshold(MotionEvent actionMove) {
    BlockView touchedView = mPendingDrag.getTouchedBlockView();

    // Not dragging yet - compute distance from Down event and start dragging if far enough.
    @Size(2) int[] touchDownLocation = mTempScreenCoord1;
    mPendingDrag.getTouchDownScreen(touchDownLocation);

    @Size(2) int[] curScreenLocation = mTempScreenCoord2;
    touchedView.getTouchLocationOnScreen(actionMove, curScreenLocation);

    final int deltaX = touchDownLocation[0] - curScreenLocation[0];
    final int deltaY = touchDownLocation[1] - curScreenLocation[1];

    // Dragged far enough to start a drag?
    return (deltaX * deltaX + deltaY * deltaY > mTouchSlopSquared);
}
 
Example 10
Project: Customerly-Android-SDK   File: IE_JwtToken.java   View source code 6 votes vote down vote up
IE_JwtToken(@org.intellij.lang.annotations.Pattern(TOKEN_VALIDATOR_MATCHER) @Size(min = 5) @NonNull String pEncodedToken) throws IllegalArgumentException {
    super();
    this._EncodedToken = pEncodedToken;

    if(! this._EncodedToken.matches(TOKEN_VALIDATOR_MATCHER)) {
        throw new IllegalArgumentException(String.format("Wrong token format. Token: %s does not match the regex %s", pEncodedToken, TOKEN_VALIDATOR_MATCHER));
    }
    JSONObject payloadJSON = null;
    try {
        Matcher matcher = TOKEN_PAYLOAD_MATCHER.matcher(pEncodedToken);
        if (matcher.find()) {
            payloadJSON = new JSONObject(
                    new String(Base64.decode(matcher.group(1), Base64.DEFAULT), "UTF-8"));
        }
    } catch (Exception ignored) { }

    if(payloadJSON != null) {
        long tmpUserID = payloadJSON.optLong("id", -1L);
        this._UserID = tmpUserID == -1L ? null : tmpUserID;
        //noinspection WrongConstant
        this._UserType = payloadJSON.optInt("type", USER_TYPE__ANONYMOUS);
    } else {
        this._UserID = null;
        this._UserType = USER_TYPE__ANONYMOUS;
    }
}
 
Example 11
Project: sqlitemagic   File: ComplexColumn.java   View source code 6 votes vote down vote up
/**
 * Create an expression to check this column against several values.
 * <p>
 * SQL: this IN (values...)
 *
 * @param values The values to test against this column
 * @return Expression
 */
@NonNull
@CheckResult
public final Expr in(@NonNull @Size(min = 1) long... values) {
  final int length = values.length;
  if (length == 0) {
    throw new SQLException("Empty IN clause values");
  }
  final String[] args = new String[length];
  final StringBuilder sb = new StringBuilder(6 + (length << 1));
  sb.append(" IN (");
  for (int i = 0; i < length; i++) {
    if (i > 0) {
      sb.append(',');
    }
    sb.append('?');
    args[i] = Long.toString(values[i]);
  }
  sb.append(')');
  return new ExprN(this, sb.toString(), args);
}
 
Example 12
Project: sqlitemagic   File: ComplexColumn.java   View source code 6 votes vote down vote up
/**
 * Create an expression to check this column against several values.
 * <p>
 * SQL: this NOT IN (values...)
 *
 * @param values The values to test against this column
 * @return Expression
 */
@NonNull
@CheckResult
public final Expr notIn(@NonNull @Size(min = 1) long... values) {
  final int length = values.length;
  if (length == 0) {
    throw new SQLException("Empty IN clause values");
  }
  final String[] args = new String[length];
  final StringBuilder sb = new StringBuilder(10 + (length << 1));
  sb.append(" NOT IN (");
  for (int i = 0; i < length; i++) {
    if (i > 0) {
      sb.append(',');
    }
    sb.append('?');
    args[i] = Long.toString(values[i]);
  }
  sb.append(')');
  return new ExprN(this, sb.toString(), args);
}
 
Example 13
Project: sqlitemagic   File: Table.java   View source code 6 votes vote down vote up
/**
 * Create join "USING" clause.
 * <p>
 * Each of the columns specified must exist in the datasets to both the left and right
 * of the join-operator. For each pair of columns, the expression "lhs.X = rhs.X"
 * is evaluated for each row of the cartesian product as a boolean expression.
 * Only rows for which all such expressions evaluates to true are included from the
 * result set. When comparing values as a result of a USING clause, the normal rules
 * for handling affinities, collation sequences and NULL values in comparisons apply.
 * The column from the dataset on the left-hand side of the join-operator is considered
 * to be on the left-hand side of the comparison operator (=) for the purposes of
 * collation sequence and affinity precedence.
 * <p>
 * For each pair of columns identified by a USING clause, the column from the
 * right-hand dataset is omitted from the joined dataset. This is the only difference
 * between a USING clause and its equivalent ON constraint.
 *
 * @param columns
 *     Columns to use in the USING clause
 * @return Join clause
 */
@NonNull
@CheckResult
public final JoinClause using(@NonNull @Size(min = 1) final Column... columns) {
  final int colLen = columns.length;
  final StringBuilder sb = new StringBuilder(8 + colLen * 12);
  sb.append("USING (");
  for (int i = 0; i < colLen; i++) {
    if (i > 0) {
      sb.append(',');
    }
    sb.append(columns[i].name);
  }
  sb.append(')');
  return new JoinClause(this, "", sb.toString()) {
    @Override
    boolean containsColumn(@NonNull Column<?, ?, ?, ?, ?> column) {
      for (int i = 0; i < colLen; i++) {
        if (columns[i].equals(column)) {
          return true;
        }
      }
      return false;
    }
  };
}
 
Example 14
Project: sqlitemagic   File: Column.java   View source code 6 votes vote down vote up
/**
 * Create an expression to check this column against several values.
 * <p>
 * SQL: this IN (values...)
 *
 * @param values The values to test against this column
 * @return Expression
 */
@NonNull
@CheckResult
public final Expr in(@NonNull @Size(min = 1) Collection<T> values) {
  final int length = values.size();
  if (length == 0) {
    throw new SQLException("Empty IN clause values");
  }
  final String[] args = new String[length];
  final StringBuilder sb = new StringBuilder(6 + (length << 1));
  sb.append(" IN (");
  final Iterator<T> iterator = values.iterator();
  for (int i = 0; i < length; i++) {
    if (i > 0) {
      sb.append(',');
    }
    sb.append('?');
    args[i] = toSqlArg(iterator.next());
  }
  sb.append(')');
  return new ExprN(this, sb.toString(), args);
}
 
Example 15
Project: sqlitemagic   File: Column.java   View source code 6 votes vote down vote up
/**
 * Create an expression to check this column against several values.
 * <p>
 * SQL: this IN (values...)
 *
 * @param values The values to test against this column
 * @return Expression
 */
@SafeVarargs
@NonNull
@CheckResult
public final Expr in(@NonNull @Size(min = 1) T... values) {
  final int length = values.length;
  if (length == 0) {
    throw new SQLException("Empty IN clause values");
  }
  final String[] args = new String[length];
  final StringBuilder sb = new StringBuilder(6 + (length << 1));
  sb.append(" IN (");
  for (int i = 0; i < length; i++) {
    if (i > 0) {
      sb.append(',');
    }
    sb.append('?');
    args[i] = toSqlArg(values[i]);
  }
  sb.append(')');
  return new ExprN(this, sb.toString(), args);
}
 
Example 16
Project: sqlitemagic   File: Column.java   View source code 6 votes vote down vote up
/**
 * Create an expression to check this column against several values.
 * <p>
 * SQL: this NOT IN (values...)
 *
 * @param values The values to test against this column
 * @return Expression
 */
@NonNull
@CheckResult
public final Expr notIn(@NonNull @Size(min = 1) Collection<T> values) {
  final int length = values.size();
  if (length == 0) {
    throw new SQLException("Empty IN clause values");
  }
  final String[] args = new String[length];
  final StringBuilder sb = new StringBuilder(10 + (length << 1));
  sb.append(" NOT IN (");
  final Iterator<T> iterator = values.iterator();
  for (int i = 0; i < length; i++) {
    if (i > 0) {
      sb.append(',');
    }
    sb.append('?');
    args[i] = toSqlArg(iterator.next());
  }
  sb.append(')');
  return new ExprN(this, sb.toString(), args);
}
 
Example 17
Project: sqlitemagic   File: Column.java   View source code 6 votes vote down vote up
/**
 * Create an expression to check this column against several values.
 * <p>
 * SQL: this NOT IN (values...)
 *
 * @param values The values to test against this column
 * @return Expression
 */
@SafeVarargs
@NonNull
@CheckResult
public final Expr notIn(@NonNull @Size(min = 1) T... values) {
  final int length = values.length;
  if (length == 0) {
    throw new SQLException("Empty IN clause values");
  }
  final String[] args = new String[length];
  final StringBuilder sb = new StringBuilder(10 + (length << 1));
  sb.append(" NOT IN (");
  for (int i = 0; i < length; i++) {
    if (i > 0) {
      sb.append(',');
    }
    sb.append('?');
    args[i] = toSqlArg(values[i]);
  }
  sb.append(')');
  return new ExprN(this, sb.toString(), args);
}
 
Example 18
Project: material-camera   File: VideoStreamView.java   View source code 6 votes vote down vote up
@Size(value = 2)
private int[] getDimensions(int orientation, float videoWidth, float videoHeight) {
  final float aspectRatio = videoWidth / videoHeight;
  int width;
  int height;
  if (orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
      || orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
    width = getMeasuredWidth();
    height = (int) ((float) width / aspectRatio);
    if (height > getMeasuredHeight()) {
      height = getMeasuredHeight();
      width = (int) ((float) height * aspectRatio);
    }
  } else {
    height = getMeasuredHeight();
    width = (int) ((float) height * aspectRatio);
    if (width > getMeasuredWidth()) {
      width = getMeasuredWidth();
      height = (int) ((float) width / aspectRatio);
    }
  }
  return new int[] {width, height};
}
 
Example 19
Project: photo-affix   File: MainActivity.java   View source code 6 votes vote down vote up
@Size(2)
private int[] getNextBitmapSize() {
  if (selectedPhotos == null || selectedPhotos.length == 0) {
    selectedPhotos = adapter.getSelectedPhotos();
    if (selectedPhotos == null || selectedPhotos.length == 0)
      return new int[]{10, 10}; // crash workaround
  }
  traverseIndex++;
  if (traverseIndex > selectedPhotos.length - 1) return null;
  Photo nextPhoto = selectedPhotos[traverseIndex];
  BitmapFactory.Options options = new BitmapFactory.Options();
  options.inJustDecodeBounds = true;
  InputStream is = null;
  try {
    is = Util.openStream(this, nextPhoto.getUri());
    BitmapFactory.decodeStream(is, null, options);
  } catch (Exception e) {
    Util.showError(this, e);
    return new int[]{0, 0};
  } finally {
    Util.closeQuietely(is);
  }
  return new int[]{options.outWidth, options.outHeight};
}
 
Example 20
Project: android-plugin-host-sdk-for-locale   File: Plugin.java   View source code 6 votes vote down vote up
/**
 * Constructs a new instance.
 *
 * @param type              the type of the plug-in.
 * @param packageName       the package name of the plug-in.
 * @param activityClassName the class name of the plug-in's edit
 *                          {@code Activity}.
 * @param receiverClassName The class name of the plug-in's
 *                          {@code BroadcastReceiver}.
 * @param versionCode       The versionCode of the plug-in's package.
 * @param configuration     Configuration for the plug-in.
 */
public Plugin(@NonNull final PluginType type, @NonNull @Size(min = 1) final String packageName,
              @Size(min = 1) @NonNull final String activityClassName, @NonNull @Size(min = 1) final String receiverClassName,
              final int versionCode, @NonNull final PluginConfiguration configuration) {
    assertNotNull(type, "type"); //$NON-NLS-1$
    assertNotEmpty(packageName, "packageName"); //$NON-NLS-1$
    assertNotEmpty(activityClassName, "activityClassName"); //$NON-NLS-1$
    assertNotEmpty(receiverClassName, "receiverClassName"); //$NON-NLS-1$
    assertNotNull(configuration, "configuration"); //$NON-NLS-1$

    mType = type;
    mPackageName = packageName;
    mActivityClassName = activityClassName;
    mReceiverClassName = receiverClassName;
    mRegistryName = generateRegistryName(packageName, activityClassName);
    mVersionCode = versionCode;
    mConfiguration = configuration;
}
 
Example 21
Project: android_Skeleton   File: ApplicationHelper.java   View source code 6 votes vote down vote up
@Size(3)
@Nullable
public static Integer[] semanticVersions() {
    final String versionName = versionName();
    if (versionName == null) {
        return null;
    }
    if (! versionName.matches("^\\d+\\.\\d+\\.\\d+$")) {
        LogHelper.warning("Not semantic versioning");
        return null;
    }
    final String[] versionNames = versionName.split("\\.");
    return new Integer[] {
            Integer.valueOf(versionNames[0]),
            Integer.valueOf(versionNames[1]),
            Integer.valueOf(versionNames[2])
    };
}
 
Example 22
Project: yjPlay   File: MediaSourceBuilder.java   View source code 5 votes vote down vote up
/****
 * @param indexType 设置当前索引视频屏蔽进度
 * @param firstVideoUri 预览的视频
 * @param secondVideoUri 第二个视频
 */
public void setMediaUri(@Size(min = 0) int indexType, @NonNull Uri firstVideoUri, @NonNull Uri secondVideoUri) {
    this.indexType = indexType;
    DynamicConcatenatingMediaSource source = new DynamicConcatenatingMediaSource();
    source.addMediaSource(initMediaSource(firstVideoUri));
    source.addMediaSource(initMediaSource(secondVideoUri));
    mediaSource = source;
}
 
Example 23
Project: DebugOverlay-Android   File: LogcatViewModule.java   View source code 5 votes vote down vote up
public LogcatViewModule(@LayoutRes int layoutResId, @Size(min=1,max=100) int maxLines,
                         LogcatLineFilter lineFilter, LogcatLineColorScheme colorScheme) {
    super(layoutResId);
    this.maxLines = maxLines;
    this.lineFilter = lineFilter;
    this.colorScheme = colorScheme;
}
 
Example 24
Project: android_ui   File: TintManager.java   View source code 5 votes vote down vote up
/**
 * Obtains an array of colors from the current theme containing colors for control's normal,
 * disabled and error state.
 *
 * @param context Context used to access current theme and process also its attributes.
 * @return Array with following colors:
 * <ul>
 * <li>[{@link #THEME_COLOR_INDEX_NORMAL}] = {@link R.attr#colorControlNormal colorControlNormal}</li>
 * <li>[{@link #THEME_COLOR_INDEX_DISABLED}] = colorControlNormal with alpha value of {@link android.R.attr#disabledAlpha android:disabledAlpha}</li>
 * <li>[{@link #THEME_COLOR_INDEX_ERROR}] = {@link R.attr#uiColorErrorHighlight uiColorErrorHighlight}</li>
 * </ul>
 */
@Size(3)
private static int[] obtainThemeColors(Context context) {
	final TypedValue typedValue = new TypedValue();
	final Resources.Theme theme = context.getTheme();
	final boolean isDarkTheme = !theme.resolveAttribute(R.attr.isLightTheme, typedValue, true) || typedValue.data == 0;
	final TypedArray typedArray = context.obtainStyledAttributes(null, R.styleable.Ui_Theme_Tint);
	int colorNormal = isDarkTheme ? COLOR_NORMAL : COLOR_NORMAL_LIGHT;
	int colorDisabled = isDarkTheme ? COLOR_DISABLED : COLOR_DISABLED_LIGHT;
	int colorError = COLOR_ERROR;
	if (typedArray != null) {
		final int n = typedArray.getIndexCount();
		for (int i = 0; i < n; i++) {
			final int index = typedArray.getIndex(i);
			if (index == R.styleable.Ui_Theme_Tint_colorControlNormal) {
				colorNormal = typedArray.getColor(index, colorNormal);
			} else if (index == R.styleable.Ui_Theme_Tint_android_disabledAlpha) {
				colorDisabled = Colors.withAlpha(colorNormal, typedArray.getFloat(index, ALPHA_RATIO_DISABLED));
			} else if (index == R.styleable.Ui_Theme_Tint_uiColorErrorHighlight) {
				colorError = typedArray.getColor(index, colorError);
			}
		}
		typedArray.recycle();
	}
	return new int[] {
			colorNormal,
			colorDisabled,
			colorError
	};
}
 
Example 25
Project: mapbox-navigation-android   File: NavigationMapRoute.java   View source code 5 votes vote down vote up
/**
 * Provide a list of {@link DirectionsRoute}s, the primary route will default to the first route
 * in the directions route list. All other routes in the list will be drawn on the map using the
 * alternative route style.
 *
 * @param directionsRoutes a list of direction routes, first one being the primary and the rest of
 *                         the routes are considered alternatives.
 * @since 0.8.0
 */
public void addRoutes(@NonNull @Size(min = 1) List<DirectionsRoute> directionsRoutes) {
  this.directionsRoutes = directionsRoutes;
  primaryRouteIndex = 0;
  if (!layerIds.isEmpty()) {
    for (String id : layerIds) {
      mapboxMap.removeLayer(id);
    }
  }
  featureCollections.clear();
  generateFeatureCollectionList(directionsRoutes);
  drawRoutes();
  addDirectionWaypoints();
}
 
Example 26
Project: hey-permission   File: HeyPermission.java   View source code 5 votes vote down vote up
private static void notifyAlreadyHasPermissions(
        @NonNull BasePermissionInvoker invoker, @IntRange(from = 0) int requestCode,
        @Size(min = 1) @NonNull String... permissions) {
    final int[] grantResults = new int[permissions.length];
    for (int i = 0; i < permissions.length; i++) {
        grantResults[i] = PackageManager.PERMISSION_GRANTED;
    }
    onRequestPermissionsResult(invoker, requestCode, permissions, grantResults);
}
 
Example 27
Project: hey-permission   File: HeyPermission.java   View source code 5 votes vote down vote up
private static void onRequestPermissionsResult(
        @NonNull BasePermissionInvoker invoker, @IntRange(from = 0) int requestCode,
        @Size(min = 1) @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (!invoker.needHandleThisRequestCode(requestCode)) {
        return;
    }

    final List<String> granted = new ArrayList<>();
    final List<String> denied = new ArrayList<>();
    for (int i = 0; i < permissions.length; i++) {
        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
            granted.add(permissions[i]);
        } else {
            denied.add(permissions[i]);
        }
    }

    if (denied.isEmpty()) {
        // all permissions were granted
        invokePermissionsResultMethod(PermissionsGranted.class, invoker, requestCode, granted);
        invokePermissionsResultMethod(PermissionsResult.class, invoker, requestCode, denied);
        return;
    }
    final String[] deniedPermissions = denied.toArray(new String[denied.size()]);
    boolean neverAskAgain = true;
    if (invoker.shouldShowRequestPermissionRationale(deniedPermissions)) {
        neverAskAgain = false;
        if (invokeShowRationaleMethod(true, invoker, requestCode, deniedPermissions)) {
            return;
        }
    }
    if (neverAskAgain) {
        invokePermissionsResultMethod(PermissionsNeverAskAgain.class,
                invoker, requestCode, denied);
    } else {
        invokePermissionsResultMethod(PermissionsDenied.class, invoker, requestCode, denied);
    }
    invokePermissionsResultMethod(PermissionsResult.class, invoker, requestCode, denied);
}
 
Example 28
Project: hey-permission   File: HeyPermission.java   View source code 5 votes vote down vote up
private static boolean invokeShowRationaleMethod(
        boolean callOnResult, @NonNull BasePermissionInvoker invoker, @IntRange(from = 0) int requestCode,
        @Size(min = 1) @NonNull String... permissions) {
    final Object receiver = invoker.getDelegate();
    return receiver instanceof RationaleCallback
            && ((RationaleCallback) receiver).onShowRationale(invoker, requestCode, permissions,
            callOnResult);
}
 
Example 29
Project: Blockly   File: WorkspaceHelper.java   View source code 5 votes vote down vote up
/**
 * Converts a point in screen coordinates to virtual view coordinates.
 *
 * @param screenPositionIn Input coordinates of a location in absolute coordinates on the
 * screen.
 * @param viewPositionOut Output coordinates of the same location in {@link WorkspaceView},
 * expressed with respect to the virtual view coordinate system.
 */
public void screenToVirtualViewCoordinates(@Size(2) int[] screenPositionIn,
                                           ViewPoint viewPositionOut) {
    mWorkspaceView.getLocationOnScreen(mTempIntArray2);
    viewPositionOut.x =
            (int) ((screenPositionIn[0] - mTempIntArray2[0]) / mWorkspaceView.getScaleX());
    viewPositionOut.y =
            (int) ((screenPositionIn[1] - mTempIntArray2[1]) / mWorkspaceView.getScaleY());
}
 
Example 30
Project: PasscodeView   File: KeyNamesBuilder.java   View source code 5 votes vote down vote up
@SuppressWarnings("Range")
@Size(Constants.NO_OF_KEY_BOARD_ROWS * Constants.NO_OF_KEY_BOARD_COLUMNS)
String[][] build() {
    return new String[][]{{mKeyOne, mKeyFour, mKeySeven, ""},
            {mKeyTwo, mKeyFive, mKeyEight, mKeyZero},
            {mKeyThree, mKeySix, mKeyNine, BACKSPACE_TITLE}};
}
 
Example 31
Project: condom   File: CondomContext.java   View source code 5 votes vote down vote up
private CondomContext(final CondomCore condom, final @Nullable Context app_context, final @Nullable @Size(max=16) String tag) {
	super(condom.mBase);
	final Context base = condom.mBase;
	mCondom = condom;
	mApplicationContext = app_context != null ? app_context : this;
	mBaseContext = new Lazy<Context>() { @Override protected Context create() {
		return new PseudoContextImpl(CondomContext.this);
	}};
	TAG = CondomCore.buildLogTag("Condom", "Condom.", tag);
}
 
Example 32
Project: CheckIn   File: ParallaxLayerLayout.java   View source code 5 votes vote down vote up
public void updateTranslations(@Size(2) float[] translations) {
    if (Math.abs(translations[0]) > 1 || Math.abs(translations[1]) > 1) {
        throw new IllegalArgumentException("Translation values must be between 1.0 and -1.0");
    }

    final int childCount = getChildCount();
    for (int i = childCount - 1; i >= 0; i--) {
        View child = getChildAt(i);
        float[] translationsPx = calculateFinalTranslationPx(child, translations);
        child.setTranslationX(translationsPx[0]);
        child.setTranslationY(translationsPx[1]);
    }
}
 
Example 33
Project: CheckIn   File: ParallaxLayerLayout.java   View source code 5 votes vote down vote up
@Size(2)
private float[] calculateFinalTranslationPx(View child, @Size(2) float[] translations) {
    LayoutParams lp = (LayoutParams) child.getLayoutParams();
    int xSign = translations[0] > 0 ? 1 : -1;
    int ySign = translations[1] > 0 ? 1 : -1;

    float translationX =
            xSign * lp.offsetPx * interpolator.getInterpolation(Math.abs(translations[0])) * scaleX;
    float translationY =
            ySign * lp.offsetPx * interpolator.getInterpolation(Math.abs(translations[1])) * scaleY;

    return new float[]{translationX, translationY};
}
 
Example 34
Project: OSchina_resources_android   File: TweetPublishActivity.java   View source code 5 votes vote down vote up
public static void show(Context context, @Size(2) int[] viewLocationOnScreen,
                        @Size(2) int[] viewSize, String defaultContent, About.Share share, String localImageUrl) {
    // Check login before show
    if (!AccountHelper.isLogin()) {
        UIHelper.showLoginActivity(context);
        return;
    }

    Intent intent = new Intent(context, TweetPublishActivity.class);

    if (viewLocationOnScreen != null) {
        intent.putExtra("location", viewLocationOnScreen);
    }
    if (viewSize != null) {
        intent.putExtra("size", viewSize);
    }
    if (defaultContent != null) {
        intent.putExtra("defaultContent", defaultContent);
    }
    if (share != null) {
        intent.putExtra("aboutShare", share);
    }
    if (!TextUtils.isEmpty(localImageUrl)) {
        intent.putExtra("imageUrl", localImageUrl);
    }
    context.startActivity(intent);
}
 
Example 35
Project: AndZilla   File: EasyPermission.java   View source code 5 votes vote down vote up
public static boolean hasPermission(AppCompatActivity activity, @Size(min = 1) String[] permissions) {
    for (String permission : permissions) {
        if (ActivityCompat.checkSelfPermission(activity.getApplicationContext(), permission)
                != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
    }
    return true;
}
 
Example 36
Project: GSYVideoPlayer   File: IjkExo2MediaPlayer.java   View source code 5 votes vote down vote up
/**
 * 倍速播放
 *
 * @param speed 倍速播放,默认为1
 * @param pitch 音量缩放,默认为1,修改会导致声音变调
 */
public void setSpeed(@Size(min = 0) float speed, @Size(min = 0) float pitch) {
    PlaybackParameters playbackParameters = new PlaybackParameters(speed, pitch);
    mSpeedPlaybackParameters = playbackParameters;
    if (mInternalPlayer != null) {
        mInternalPlayer.setPlaybackParameters(playbackParameters);
    }
}
 
Example 37
Project: Muzesto   File: Ask.java   View source code 5 votes vote down vote up
public Ask forPermissions(@NonNull @Size(min = 1) String... permissions) {
    if (permissions == null || permissions.length == 0) {
        throw new IllegalArgumentException("The permissions to request are missing");
    }
    this.permissions = permissions;
    return this;
}
 
Example 38
Project: material   File: PatternView.java   View source code 5 votes vote down vote up
public PatternView setDotsSize(@Size(min = 1) int size) {
    if (size != 0) {
        this.mDotSize = size;
    }

    return this;
}
 
Example 39
Project: material   File: PatternView.java   View source code 5 votes vote down vote up
public PatternView setDotsSizePressed(@Size(min = 1) int size) {
    if (size != 0) {
        this.mDotSizePressed = size;
    }

    return this;
}
 
Example 40
Project: prayer-times-android   File: Utils.java   View source code 5 votes vote down vote up
@NonNull
public static String getLanguage(@Size(min = 1) String... allow) {
    Locale lang = Utils.getLocale();
    Locale[] locales = new Locale[allow.length];
    for (int i = 0; i < allow.length; i++) {
        locales[i] = new Locale(allow[i]);
    }

    for (int i = 0; i < locales.length; i++) {
        if (lang.getLanguage().equals(locales[i].getLanguage())) return allow[i];
    }

    return allow[0];
}