Example usage for android.view View getResources

List of usage examples for android.view View getResources

Introduction

In this page you can find the example usage for android.view View getResources.

Prototype

public Resources getResources() 

Source Link

Document

Returns the resources associated with this view.

Usage

From source file:com.geecko.QuickLyric.adapter.IntroScreenSlidePagerAdapter.java

@SuppressWarnings({ "deprecation", "ResourceAsColor" })
@Override/*from   w ww. j a v a  2s . co m*/
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    View tutorialLayout = mActivity.findViewById(R.id.tutorial_layout);
    ArgbEvaluator evaluator = new ArgbEvaluator();
    Object background = position < getCount() - 1
            ? evaluator.evaluate(positionOffset, mActivity.getResources().getColor(colors[position]),
                    mActivity.getResources().getColor(colors[position + 1]))
            : mActivity.getResources().getColor(colors[position]);
    tutorialLayout.setBackgroundColor((int) background);
    MainActivity.setNavBarColor(mActivity.getWindow(), mActivity.getTheme(),
            (int) evaluator.evaluate(0.5f, mActivity.getResources().getColor(R.color.action_dark), background));
    MainActivity.setStatusBarColor(mActivity.getWindow(), mActivity.getTheme(),
            (int) evaluator.evaluate(0.5f, mActivity.getResources().getColor(R.color.action_dark), background));

    View bigFab = tutorialLayout.findViewById(R.id.big_fab);
    View handImage = tutorialLayout.findViewById(R.id.musicid_demo_hand_image);
    View soundImage = tutorialLayout.findViewById(R.id.musicid_demo_sound_image);
    View redKey = tutorialLayout.findViewById(R.id.intro_4_red_key);
    View yellowKey = tutorialLayout.findViewById(R.id.intro_4_yellow_key);
    View gearA = tutorialLayout.findViewById(R.id.redGear);
    View gearB = tutorialLayout.findViewById(R.id.blueGear);

    BubblePopImageView tableImageView = (BubblePopImageView) tutorialLayout.findViewById(R.id.table);
    position = rightToLeft ? getCount() - 1 - position : position;
    if (rightToLeft && positionOffset > 0.0) {
        position -= 1;
        positionOffset = 1f - positionOffset;
        positionOffsetPixels = (int) (positionOffset * mPager.getWidth());
    }

    switch (position) {
    case 0:
        if (tableImageView != null) {
            tableImageView.setProgress(positionOffset);
            tableImageView.setTranslationX((rightToLeft ? -1f : 1f) * (1f - positionOffset)
                    * (tableImageView.getMeasuredWidth() / 3f));
        }
        break;
    case 1:
        if (tableImageView != null) {
            tableImageView.setProgress(1f);
            tableImageView.setTranslationX((rightToLeft ? 0.15f : -0.4f) * positionOffsetPixels);
        }
        if (bigFab != null) {
            bigFab.setTranslationX(
                    (rightToLeft ? -1f : 1f) * (1f - positionOffset) * (bigFab.getMeasuredWidth() / 3f));
            if (mCurrentPage == 1 ^ rightToLeft)
                bigFab.setRotation(positionOffset * 360f);
            else
                bigFab.setRotation((1f - positionOffset) * 360f);
        }
        break;
    case 2:
        if (bigFab != null)
            ((View) bigFab.getParent()).setTranslationX((!rightToLeft ? -0.4f : 0.4f) * positionOffsetPixels);
        if (soundImage != null && handImage != null) {
            soundImage.setTranslationX(300f - 300f * positionOffset);
            handImage.setTranslationX(-400f + 400f * positionOffset);
        }
        break;
    case 3:
        if (redKey != null && yellowKey != null) {
            if (redKey.getMeasuredHeight() < redKey.getResources().getDimensionPixelSize(R.dimen.dp) * 15) {
                redKey.setVisibility(View.INVISIBLE);
                yellowKey.setVisibility(View.INVISIBLE);
                break;
            } else {
                redKey.setVisibility(View.VISIBLE);
                yellowKey.setVisibility(View.VISIBLE);
            }
            redKey.setTranslationY(330f * (1 - positionOffset));
            yellowKey.setTranslationY(290f * Math.min(1.3f * (1 - positionOffset), 1.0f));
            yellowKey.setTranslationX(105f * Math.min(1.3f * (1 - positionOffset), 1.0f));
        }
        if (3 == count - 2 && gearA != null && gearB != null) {
            gearA.setRotation(-180f * positionOffset);
            gearB.setRotation(180f * positionOffset);
        }
        break;
    case 4:
        if (gearA != null && gearB != null) {
            gearA.setRotation(-180f * positionOffset);
            gearB.setRotation(180f * positionOffset);
        }
        break;
    }
}

From source file:com.nickandjerry.dynamiclayoutinflator.DynamicLayoutInflator.java

public static void createViewRunnables() {
    viewRunnables = new HashMap<>(30);
    viewRunnables.put("scaleType", new ViewParamRunnable() {
        @Override//from  w w  w  . j  a va2 s  .c o  m
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof ImageView) {
                ImageView.ScaleType scaleType = ((ImageView) view).getScaleType();
                switch (value.toLowerCase()) {
                case "center":
                    scaleType = ImageView.ScaleType.CENTER;
                    break;
                case "center_crop":
                    scaleType = ImageView.ScaleType.CENTER_CROP;
                    break;
                case "center_inside":
                    scaleType = ImageView.ScaleType.CENTER_INSIDE;
                    break;
                case "fit_center":
                    scaleType = ImageView.ScaleType.FIT_CENTER;
                    break;
                case "fit_end":
                    scaleType = ImageView.ScaleType.FIT_END;
                    break;
                case "fit_start":
                    scaleType = ImageView.ScaleType.FIT_START;
                    break;
                case "fit_xy":
                    scaleType = ImageView.ScaleType.FIT_XY;
                    break;
                case "matrix":
                    scaleType = ImageView.ScaleType.MATRIX;
                    break;
                }
                ((ImageView) view).setScaleType(scaleType);
            }
        }
    });
    viewRunnables.put("orientation", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof LinearLayout) {
                ((LinearLayout) view).setOrientation(
                        value.equals("vertical") ? LinearLayout.VERTICAL : LinearLayout.HORIZONTAL);
            }
        }
    });
    viewRunnables.put("text", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                ((TextView) view).setText(value);
            }
        }
    });
    viewRunnables.put("textSize", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_PX,
                        DimensionConverter.stringToDimension(value, view.getResources().getDisplayMetrics()));
            }
        }
    });
    viewRunnables.put("textColor", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                ((TextView) view).setTextColor(parseColor(view, value));
            }
        }
    });
    viewRunnables.put("textStyle", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                int typeFace = Typeface.NORMAL;
                if (value.contains("bold"))
                    typeFace |= Typeface.BOLD;
                else if (value.contains("italic"))
                    typeFace |= Typeface.ITALIC;
                ((TextView) view).setTypeface(null, typeFace);
            }
        }
    });
    viewRunnables.put("textAlignment", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                int alignment = View.TEXT_ALIGNMENT_TEXT_START;
                switch (value) {
                case "center":
                    alignment = View.TEXT_ALIGNMENT_CENTER;
                    break;
                case "left":
                case "textStart":
                    break;
                case "right":
                case "textEnd":
                    alignment = View.TEXT_ALIGNMENT_TEXT_END;
                    break;
                }
                view.setTextAlignment(alignment);
            } else {
                int gravity = Gravity.LEFT;
                switch (value) {
                case "center":
                    gravity = Gravity.CENTER;
                    break;
                case "left":
                case "textStart":
                    break;
                case "right":
                case "textEnd":
                    gravity = Gravity.RIGHT;
                    break;
                }
                ((TextView) view).setGravity(gravity);
            }
        }
    });
    viewRunnables.put("ellipsize", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                TextUtils.TruncateAt where = TextUtils.TruncateAt.END;
                switch (value) {
                case "start":
                    where = TextUtils.TruncateAt.START;
                    break;
                case "middle":
                    where = TextUtils.TruncateAt.MIDDLE;
                    break;
                case "marquee":
                    where = TextUtils.TruncateAt.MARQUEE;
                    break;
                case "end":
                    break;
                }
                ((TextView) view).setEllipsize(where);
            }
        }
    });
    viewRunnables.put("singleLine", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                ((TextView) view).setSingleLine();
            }
        }
    });
    viewRunnables.put("hint", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof EditText) {
                ((EditText) view).setHint(value);
            }
        }
    });
    viewRunnables.put("inputType", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof TextView) {
                int inputType = 0;
                switch (value) {
                case "textEmailAddress":
                    inputType |= InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
                    break;
                case "number":
                    inputType |= InputType.TYPE_CLASS_NUMBER;
                    break;
                case "phone":
                    inputType |= InputType.TYPE_CLASS_PHONE;
                    break;
                }
                if (inputType > 0)
                    ((TextView) view).setInputType(inputType);
            }
        }
    });
    viewRunnables.put("gravity", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            int gravity = parseGravity(value);
            if (view instanceof TextView) {
                ((TextView) view).setGravity(gravity);
            } else if (view instanceof LinearLayout) {
                ((LinearLayout) view).setGravity(gravity);
            } else if (view instanceof RelativeLayout) {
                ((RelativeLayout) view).setGravity(gravity);
            }
        }
    });
    viewRunnables.put("src", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            if (view instanceof ImageView) {
                String imageName = value;
                if (imageName.startsWith("//"))
                    imageName = "http:" + imageName;
                if (imageName.startsWith("http")) {
                    if (imageLoader != null) {
                        if (attrs.containsKey("cornerRadius")) {
                            int radius = DimensionConverter.stringToDimensionPixelSize(
                                    attrs.get("cornerRadius"), view.getResources().getDisplayMetrics());
                            imageLoader.loadRoundedImage((ImageView) view, imageName, radius);
                        } else {
                            imageLoader.loadImage((ImageView) view, imageName);
                        }
                    }
                } else if (imageName.startsWith("@drawable/")) {
                    imageName = imageName.substring("@drawable/".length());
                    ((ImageView) view).setImageDrawable(getDrawableByName(view, imageName));
                }
            }
        }
    });
    viewRunnables.put("visibility", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            int visibility = View.VISIBLE;
            String visValue = value.toLowerCase();
            if (visValue.equals("gone"))
                visibility = View.GONE;
            else if (visValue.equals("invisible"))
                visibility = View.INVISIBLE;
            view.setVisibility(visibility);
        }
    });
    viewRunnables.put("clickable", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            view.setClickable(value.equals("true"));
        }
    });
    viewRunnables.put("tag", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            // Sigh, this is dangerous because we use tags for other purposes
            if (view.getTag() == null)
                view.setTag(value);
        }
    });
    viewRunnables.put("onClick", new ViewParamRunnable() {
        @Override
        public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) {
            view.setOnClickListener(getClickListener(parent, value));
        }
    });
}

From source file:com.bachhuberdesign.deckbuildergwent.util.FabTransform.java

@Override
public Animator createAnimator(final ViewGroup sceneRoot, final TransitionValues startValues,
        final TransitionValues endValues) {
    if (startValues == null || endValues == null)
        return null;

    final Rect startBounds = (Rect) startValues.values.get(PROP_BOUNDS);
    final Rect endBounds = (Rect) endValues.values.get(PROP_BOUNDS);

    final boolean fromFab = endBounds.width() > startBounds.width();
    final View view = endValues.view;
    final Rect dialogBounds = fromFab ? endBounds : startBounds;
    final Interpolator fastOutSlowInInterpolator = AnimUtils.getFastOutSlowInInterpolator();
    final long duration = getDuration();
    final long halfDuration = duration / 2;
    final long twoThirdsDuration = duration * 2 / 3;

    if (!fromFab) {
        // Force measure / layout the dialog back to it's original bounds
        view.measure(makeMeasureSpec(startBounds.width(), View.MeasureSpec.EXACTLY),
                makeMeasureSpec(startBounds.height(), View.MeasureSpec.EXACTLY));
        view.layout(startBounds.left, startBounds.top, startBounds.right, startBounds.bottom);
    }//from   w w w . jav  a 2 s.c  om

    final int translationX = startBounds.centerX() - endBounds.centerX();
    final int translationY = startBounds.centerY() - endBounds.centerY();
    if (fromFab) {
        view.setTranslationX(translationX);
        view.setTranslationY(translationY);
    }

    // Add a color overlay to fake appearance of the FAB
    final ColorDrawable fabColor = new ColorDrawable(color);
    fabColor.setBounds(0, 0, dialogBounds.width(), dialogBounds.height());
    if (!fromFab)
        fabColor.setAlpha(0);
    view.getOverlay().add(fabColor);

    // Add an icon overlay again to fake the appearance of the FAB
    final Drawable fabIcon = ContextCompat.getDrawable(sceneRoot.getContext(), icon).mutate();
    final int iconLeft = (dialogBounds.width() - fabIcon.getIntrinsicWidth()) / 2;
    final int iconTop = (dialogBounds.height() - fabIcon.getIntrinsicHeight()) / 2;
    fabIcon.setBounds(iconLeft, iconTop, iconLeft + fabIcon.getIntrinsicWidth(),
            iconTop + fabIcon.getIntrinsicHeight());
    if (!fromFab)
        fabIcon.setAlpha(0);
    view.getOverlay().add(fabIcon);

    // Since the view that's being transition to always seems to be on the top (z-order), we have
    // to make a copy of the "from" view and put it in the "to" view's overlay, then fade it out.
    // There has to be another way to do this, right?
    Drawable dialogView = null;
    if (!fromFab) {
        startValues.view.setDrawingCacheEnabled(true);
        startValues.view.buildDrawingCache();
        Bitmap viewBitmap = startValues.view.getDrawingCache();
        dialogView = new BitmapDrawable(view.getResources(), viewBitmap);
        dialogView.setBounds(0, 0, dialogBounds.width(), dialogBounds.height());
        view.getOverlay().add(dialogView);
    }

    // Circular clip from/to the FAB size
    final Animator circularReveal;
    if (fromFab) {
        circularReveal = ViewAnimationUtils.createCircularReveal(view, view.getWidth() / 2,
                view.getHeight() / 2, startBounds.width() / 2,
                (float) Math.hypot(endBounds.width() / 2, endBounds.height() / 2));
        circularReveal.setInterpolator(AnimUtils.getFastOutLinearInInterpolator());
    } else {
        circularReveal = ViewAnimationUtils.createCircularReveal(view, view.getWidth() / 2,
                view.getHeight() / 2, (float) Math.hypot(startBounds.width() / 2, startBounds.height() / 2),
                endBounds.width() / 2);
        circularReveal.setInterpolator(AnimUtils.getLinearOutSlowInInterpolator());

        // Persist the end clip i.e. stay at FAB size after the reveal has run
        circularReveal.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                final ViewOutlineProvider fabOutlineProvider = view.getOutlineProvider();

                view.setOutlineProvider(new ViewOutlineProvider() {
                    boolean hasRun = false;

                    @Override
                    public void getOutline(final View view, Outline outline) {
                        final int left = (view.getWidth() - endBounds.width()) / 2;
                        final int top = (view.getHeight() - endBounds.height()) / 2;

                        outline.setOval(left, top, left + endBounds.width(), top + endBounds.height());

                        if (!hasRun) {
                            hasRun = true;
                            view.setClipToOutline(true);

                            // We have to remove this as soon as it's laid out so we can get the shadow back
                            view.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
                                @Override
                                public boolean onPreDraw() {
                                    if (view.getWidth() == endBounds.width()
                                            && view.getHeight() == endBounds.height()) {
                                        view.setOutlineProvider(fabOutlineProvider);
                                        view.setClipToOutline(false);
                                        view.getViewTreeObserver().removeOnPreDrawListener(this);
                                        return true;
                                    }

                                    return true;
                                }
                            });
                        }
                    }
                });
            }
        });
    }
    circularReveal.setDuration(duration);

    // Translate to end position along an arc
    final Animator translate = ObjectAnimator.ofFloat(view, View.TRANSLATION_X, View.TRANSLATION_Y,
            fromFab ? getPathMotion().getPath(translationX, translationY, 0, 0)
                    : getPathMotion().getPath(0, 0, -translationX, -translationY));
    translate.setDuration(duration);
    translate.setInterpolator(fastOutSlowInInterpolator);

    // Fade contents of non-FAB view in/out
    List<Animator> fadeContents = null;
    if (view instanceof ViewGroup) {
        final ViewGroup vg = ((ViewGroup) view);
        fadeContents = new ArrayList<>(vg.getChildCount());
        for (int i = vg.getChildCount() - 1; i >= 0; i--) {
            final View child = vg.getChildAt(i);
            final Animator fade = ObjectAnimator.ofFloat(child, View.ALPHA, fromFab ? 1f : 0f);
            if (fromFab) {
                child.setAlpha(0f);
            }
            fade.setDuration(twoThirdsDuration);
            fade.setInterpolator(fastOutSlowInInterpolator);
            fadeContents.add(fade);
        }
    }

    // Fade in/out the fab color & icon overlays
    final Animator colorFade = ObjectAnimator.ofInt(fabColor, "alpha", fromFab ? 0 : 255);
    final Animator iconFade = ObjectAnimator.ofInt(fabIcon, "alpha", fromFab ? 0 : 255);
    if (!fromFab) {
        colorFade.setStartDelay(halfDuration);
        iconFade.setStartDelay(halfDuration);
    }
    colorFade.setDuration(halfDuration);
    iconFade.setDuration(halfDuration);
    colorFade.setInterpolator(fastOutSlowInInterpolator);
    iconFade.setInterpolator(fastOutSlowInInterpolator);

    // Run all animations together
    final AnimatorSet transition = new AnimatorSet();
    transition.playTogether(circularReveal, translate, colorFade, iconFade);
    transition.playTogether(fadeContents);
    if (dialogView != null) {
        final Animator dialogViewFade = ObjectAnimator.ofInt(dialogView, "alpha", 0)
                .setDuration(twoThirdsDuration);
        dialogViewFade.setInterpolator(fastOutSlowInInterpolator);
        transition.playTogether(dialogViewFade);
    }
    transition.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            // Clean up
            view.getOverlay().clear();

            if (!fromFab) {
                view.setTranslationX(0);
                view.setTranslationY(0);
                view.setTranslationZ(0);

                view.measure(makeMeasureSpec(endBounds.width(), View.MeasureSpec.EXACTLY),
                        makeMeasureSpec(endBounds.height(), View.MeasureSpec.EXACTLY));
                view.layout(endBounds.left, endBounds.top, endBounds.right, endBounds.bottom);
            }

        }
    });
    return new AnimUtils.NoPauseAnimator(transition);
}

From source file:fr.eoit.activity.util.StationListViewBinder.java

@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
    int viewId = view.getId();
    boolean isNull = cursor.isNull(columnIndex);

    TextView textView;/*w  w w . j  a  v a2s.  co m*/
    ImageView imageView;
    String[] stationNameArray;
    double price;
    long volume;
    int role, stationId = cursor.getInt(cursor.getColumnIndexOrThrow(Station._ID));

    switch (viewId) {
    case R.id.station_name:
        stationName = cursor.getString(columnIndex);
        textView = (TextView) view;
        stationNameArray = stationName.split(" - ");
        textView.setText(stationNameArray[stationNameArray.length - 1]);
        break;

    case R.id.location_name:
        String regionName = cursor.getString(columnIndex);
        textView = (TextView) view;

        stationNameArray = stationName.split(" - ");
        StringBuilder sb = new StringBuilder(regionName);
        if (stationNameArray.length == 2) {
            sb.append(" > ").append(stationNameArray[0]);
        } else if (stationNameArray.length == 3) {
            sb.append(" > ").append(stationNameArray[0]).append(" - ").append(stationNameArray[1]);
        }

        textView.setText(sb.toString());
        break;

    case R.id.station_icon:
        int id = cursor.getInt(columnIndex);
        imageView = (ImageView) view;
        IconUtil.initRender(id, imageView);
        break;

    case R.id.favorite_station:
        boolean favorite = cursor.getInt(columnIndex) == 1;
        CheckBox favoriteCheckBox = (CheckBox) view;
        favoriteCheckBox.setChecked(favorite);
        favoriteCheckBox.setOnCheckedChangeListener(
                new FavoriteStationsOnCheckedChangeListener(stationId, favoriteCheckBox.getContext()));
        break;

    case R.id.station_prod_icon:
        role = cursor.getInt(columnIndex);
        imageView = (ImageView) view;

        if (role == EOITConst.Stations.TRADE_ROLE || isNull) {
            view.setVisibility(View.GONE);
        } else {
            view.setVisibility(View.VISIBLE);
        }
        break;

    case R.id.station_trade_icon:
        role = cursor.getInt(columnIndex);
        imageView = (ImageView) view;

        if (role == EOITConst.Stations.PRODUCTION_ROLE || isNull) {
            view.setVisibility(View.GONE);
        } else {
            view.setVisibility(View.VISIBLE);
        }
        break;

    case R.id.corp_standing:
        float standing = cursor.getFloat(columnIndex);
        textView = (TextView) view;
        textView.setText(nf.format(standing));
        if (standing > 0) {
            textView.setTextColor(view.getResources().getColor(R.color.green));
        } else if (standing == 0) {
            textView.setTextColor(view.getResources().getColor(R.color.grey));
        } else if (standing < 0) {
            textView.setTextColor(view.getResources().getColor(R.color.red));
        }

        break;

    case R.id.buy_price:
    case R.id.sell_price:
        price = cursor.getDouble(columnIndex);
        textView = (TextView) view;
        PricesUtils.setPrice(textView, price, true);
        break;

    case R.id.buy_volume:
    case R.id.sell_volume:
        volume = cursor.getLong(columnIndex);
        textView = (TextView) view;
        textView.setText(nfVolume.format(volume));
        break;

    default:
        throw new IllegalArgumentException("viewId : " + viewId);
    }

    return true;
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static void showMenuItemToast(final View v, final CharSequence text, final boolean isBottomBar) {
    final int[] screenPos = new int[2];
    final Rect displayFrame = new Rect();
    v.getLocationOnScreen(screenPos);/*from   w  w w .ja v  a 2  s .  co m*/
    v.getWindowVisibleDisplayFrame(displayFrame);
    final int width = v.getWidth();
    final int height = v.getHeight();
    final int screenWidth = v.getResources().getDisplayMetrics().widthPixels;
    final Toast cheatSheet = Toast.makeText(v.getContext(), text, Toast.LENGTH_SHORT);
    if (isBottomBar) {
        // Show along the bottom center
        cheatSheet.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, height);
    } else {
        // Show along the top; follow action buttons
        cheatSheet.setGravity(Gravity.TOP | Gravity.RIGHT, screenWidth - screenPos[0] - width / 2, height);
    }
    cheatSheet.show();
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static String getMapStaticImageUri(final double lat, final double lng, final View v) {
    if (v == null)
        return null;
    final int wSpec = MeasureSpec.makeMeasureSpec(v.getWidth(), MeasureSpec.UNSPECIFIED);
    final int hSpec = MeasureSpec.makeMeasureSpec(v.getHeight(), MeasureSpec.UNSPECIFIED);
    v.measure(wSpec, hSpec);/*from  w w  w .j  a  v  a  2 s  .  c  o  m*/
    return getMapStaticImageUri(lat, lng, 12, v.getMeasuredWidth(), v.getMeasuredHeight(),
            v.getResources().getConfiguration().locale);
}

From source file:org.onebusaway.android.ui.ArrivalsListAdapterStyleA.java

@Override
protected void initView(View view, ArrivalInfo stopInfo) {
    final Context context = getContext();
    final ObaArrivalInfo arrivalInfo = stopInfo.getInfo();

    TextView route = (TextView) view.findViewById(R.id.route);
    TextView destination = (TextView) view.findViewById(R.id.destination);
    TextView time = (TextView) view.findViewById(R.id.time);
    TextView status = (TextView) view.findViewById(R.id.status);
    TextView etaView = (TextView) view.findViewById(R.id.eta);
    TextView minView = (TextView) view.findViewById(R.id.eta_min);
    ViewGroup realtimeView = (ViewGroup) view.findViewById(R.id.eta_realtime_indicator);
    ImageView moreView = (ImageView) view.findViewById(R.id.more_horizontal);
    moreView.setColorFilter(context.getResources().getColor(R.color.switch_thumb_normal_material_dark));
    ImageView starView = (ImageView) view.findViewById(R.id.route_favorite);
    starView.setColorFilter(context.getResources().getColor(R.color.navdrawer_icon_tint));
    starView.setImageResource(/*  w  ww.  j a  v  a 2s .co m*/
            stopInfo.isRouteAndHeadsignFavorite() ? R.drawable.focus_star_on : R.drawable.focus_star_off);

    route.setText(arrivalInfo.getShortName());
    destination.setText(MyTextUtils.toTitleCase(arrivalInfo.getHeadsign()));
    status.setText(stopInfo.getStatusText());

    long eta = stopInfo.getEta();
    if (eta == 0) {
        etaView.setText(R.string.stop_info_eta_now);
        minView.setVisibility(View.GONE);
    } else {
        etaView.setText(String.valueOf(eta));
        minView.setVisibility(View.VISIBLE);
    }

    status.setBackgroundResource(R.drawable.round_corners_style_b_status);
    GradientDrawable d = (GradientDrawable) status.getBackground();

    Integer colorCode = stopInfo.getColor();
    int color = context.getResources().getColor(colorCode);
    if (stopInfo.getPredicted()) {
        // Show real-time indicator
        UIUtils.setRealtimeIndicatorColorByResourceCode(realtimeView, colorCode, android.R.color.transparent);
        realtimeView.setVisibility(View.VISIBLE);
    } else {
        realtimeView.setVisibility(View.INVISIBLE);
    }

    etaView.setTextColor(color);
    minView.setTextColor(color);
    d.setColor(color);

    // Set padding on status view
    int pSides = UIUtils.dpToPixels(context, 5);
    int pTopBottom = UIUtils.dpToPixels(context, 2);
    status.setPadding(pSides, pTopBottom, pSides, pTopBottom);

    time.setText(DateUtils.formatDateTime(context, stopInfo.getDisplayTime(),
            DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NO_NOON | DateUtils.FORMAT_NO_MIDNIGHT));

    ContentValues values = null;
    if (mTripsForStop != null) {
        values = mTripsForStop.getValues(arrivalInfo.getTripId());
    }
    if (values != null) {
        String reminderName = values.getAsString(ObaContract.Trips.NAME);

        TextView reminder = (TextView) view.findViewById(R.id.reminder);
        if (reminderName.length() == 0) {
            reminderName = context.getString(R.string.trip_info_noname);
        }
        reminder.setText(reminderName);
        Drawable d2 = reminder.getCompoundDrawables()[0];
        d2 = DrawableCompat.wrap(d2);
        DrawableCompat.setTint(d2.mutate(), view.getResources().getColor(R.color.button_material_dark));
        reminder.setCompoundDrawables(d2, null, null, null);
        reminder.setVisibility(View.VISIBLE);
    } else {
        // Explicitly set this to invisible because we might be reusing
        // this view.
        View reminder = view.findViewById(R.id.reminder);
        reminder.setVisibility(View.GONE);
    }
}

From source file:fiskinfoo.no.sintef.fiskinfoo.Implementation.UtilityOnClickListeners.java

@Override
public OnClickListener getSubscriptionCheckBoxOnClickListener(final PropertyDescription subscription,
        final Subscription activeSubscription, final User user) {
    return new OnClickListener() {
        @Override/*from www. j  a  v  a  2  s .  c om*/
        public void onClick(final View v) {
            UtilityRowsInterface utilityRowsInterface = new UtilityRows();
            final FiskInfoUtility fiskInfoUtility = new FiskInfoUtility();

            final Dialog dialog;

            int iconId = fiskInfoUtility.subscriptionApiNameToIconId(subscription.ApiName);

            if (iconId != -1) {
                dialog = new UtilityDialogs().getDialogWithTitleIcon(v.getContext(),
                        R.layout.dialog_manage_subscription, subscription.Name, iconId);
            } else {
                dialog = new UtilityDialogs().getDialog(v.getContext(), R.layout.dialog_manage_subscription,
                        subscription.Name);
            }

            final Switch subscribedSwitch = (Switch) dialog.findViewById(R.id.manage_subscription_switch);
            final LinearLayout formatsContainer = (LinearLayout) dialog
                    .findViewById(R.id.manage_subscription_formats_container);
            final LinearLayout intervalsContainer = (LinearLayout) dialog
                    .findViewById(R.id.manage_subscription_intervals_container);
            final EditText subscriptionEmailEditText = (EditText) dialog
                    .findViewById(R.id.manage_subscription_email_edit_text);

            final Button subscribeButton = (Button) dialog.findViewById(R.id.manage_subscription_update_button);
            Button cancelButton = (Button) dialog.findViewById(R.id.manage_subscription_cancel_button);

            final boolean isSubscribed = activeSubscription != null;
            final Map<String, String> subscriptionFrequencies = new HashMap<>();

            dialog.setTitle(subscription.Name);

            if (isSubscribed) {
                subscriptionEmailEditText.setText(activeSubscription.SubscriptionEmail);

                subscribedSwitch.setVisibility(View.VISIBLE);
                subscribedSwitch.setChecked(true);
                subscribedSwitch
                        .setText(v.getResources().getString(R.string.manage_subscription_subscription_active));

                subscribedSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        System.out.println("This is checked:" + isChecked);
                        String switchText = isChecked
                                ? v.getResources().getString(R.string.manage_subscription_subscription_active)
                                : v.getResources()
                                        .getString(R.string.manage_subscription_subscription_cancellation);
                        subscribedSwitch.setText(switchText);
                    }
                });
            } else {
                subscriptionEmailEditText.setText(user.getUsername());
            }

            for (String format : subscription.Formats) {
                final RadioButtonRow row = utilityRowsInterface.getRadioButtonRow(v.getContext(), format);
                if (isSubscribed && activeSubscription.FileFormatType.equals(format)) {
                    row.setSelected(true);
                }

                formatsContainer.addView(row.getView());
            }

            for (String interval : subscription.SubscriptionInterval) {
                final RadioButtonRow row = utilityRowsInterface.getRadioButtonRow(v.getContext(),
                        SubscriptionInterval.getType(interval).toString());

                if (activeSubscription != null) {
                    row.setSelected(activeSubscription.SubscriptionIntervalName.equals(interval));
                }

                subscriptionFrequencies.put(SubscriptionInterval.getType(interval).toString(), interval);
                intervalsContainer.addView(row.getView());
            }

            if (intervalsContainer.getChildCount() == 1) {
                ((RadioButton) intervalsContainer.getChildAt(0)
                        .findViewById(R.id.radio_button_row_radio_button)).setChecked(true);
            }

            subscribeButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View subscribeButton) {
                    String subscriptionFormat = null;
                    String subscriptionInterval = null;
                    String subscriptionEmail;

                    BarentswatchApi barentswatchApi = new BarentswatchApi();
                    barentswatchApi.setAccesToken(user.getToken());
                    final IBarentswatchApi api = barentswatchApi.getApi();

                    for (int i = 0; i < formatsContainer.getChildCount(); i++) {
                        if (((RadioButton) formatsContainer.getChildAt(i)
                                .findViewById(R.id.radio_button_row_radio_button)).isChecked()) {
                            subscriptionFormat = ((TextView) formatsContainer.getChildAt(i)
                                    .findViewById(R.id.radio_button_row_text_view)).getText().toString();
                            break;
                        }
                    }

                    if (subscriptionFormat == null) {
                        Toast.makeText(v.getContext(),
                                v.getContext().getString(R.string.choose_subscription_format),
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    for (int i = 0; i < intervalsContainer.getChildCount(); i++) {
                        if (((RadioButton) intervalsContainer.getChildAt(i)
                                .findViewById(R.id.radio_button_row_radio_button)).isChecked()) {
                            subscriptionInterval = ((TextView) intervalsContainer.getChildAt(i)
                                    .findViewById(R.id.radio_button_row_text_view)).getText().toString();
                            break;
                        }
                    }

                    if (subscriptionInterval == null) {
                        Toast.makeText(v.getContext(),
                                v.getContext().getString(R.string.choose_subscription_interval),
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    subscriptionEmail = subscriptionEmailEditText.getText().toString();

                    if (!(new FiskInfoUtility().isEmailValid(subscriptionEmail))) {
                        Toast.makeText(v.getContext(), v.getContext().getString(R.string.error_invalid_email),
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (isSubscribed) {
                        if (subscribedSwitch.isChecked()) {
                            if (!(subscriptionFormat.equals(activeSubscription.FileFormatType)
                                    && activeSubscription.SubscriptionIntervalName
                                            .equals(subscriptionFrequencies.get(subscriptionInterval))
                                    && user.getUsername().equals(subscriptionEmail))) {
                                SubscriptionSubmitObject updatedSubscription = new SubscriptionSubmitObject(
                                        subscription.ApiName, subscriptionFormat, user.getUsername(),
                                        user.getUsername(), subscriptionFrequencies.get(subscriptionInterval));
                                Subscription newSubscriptionObject = api.updateSubscription(
                                        String.valueOf(activeSubscription.Id), updatedSubscription);

                                if (newSubscriptionObject != null) {
                                    ((CheckBox) v).setChecked(true);
                                }
                            }
                        } else {
                            Response response = api.deleteSubscription(String.valueOf(activeSubscription.Id));

                            if (response.getStatus() == 204) {
                                ((CheckBox) v).setChecked(false);
                                Toast.makeText(v.getContext(), R.string.subscription_update_successful,
                                        Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(v.getContext(), R.string.subscription_update_failed,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    } else {
                        SubscriptionSubmitObject newSubscription = new SubscriptionSubmitObject(
                                subscription.ApiName, subscriptionFormat, user.getUsername(),
                                user.getUsername(), subscriptionFrequencies.get(subscriptionInterval));

                        Subscription response = api.setSubscription(newSubscription);

                        if (response != null) {
                            ((CheckBox) v).setChecked(true);
                            // TODO: add to "Mine abonnementer"
                            Toast.makeText(v.getContext(), R.string.subscription_update_successful,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(v.getContext(), R.string.subscription_update_failed,
                                    Toast.LENGTH_LONG).show();
                        }
                    }

                    dialog.dismiss();
                }
            });

            cancelButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View cancelButton) {
                    ((CheckBox) v).setChecked(isSubscribed);

                    dialog.dismiss();
                }
            });

            dialog.show();

        }
    };
}

From source file:org.mdc.chess.MDChess.java

private void selectPgnSaveNewFileDialog() {
    setAutoMode(AutoMode.OFF);//  w  w w.  ja  v a 2  s  .c  o  m
    View content = View.inflate(this, R.layout.create_pgn_file, null);

    final EditText fileNameView = (EditText) content.findViewById(R.id.create_pgn_filename);
    final TextInputLayout fileNameWrapper = (TextInputLayout) content
            .findViewById(R.id.create_pgn_filename_wrapper);
    fileNameWrapper.setHint(content.getResources().getString(R.string.filename));
    fileNameView.setText("");
    final Runnable savePGN = new Runnable() {
        public void run() {
            String pgnFile = fileNameView.getText().toString();
            if ((pgnFile.length() > 0) && !pgnFile.contains(".")) {
                pgnFile += ".pgn";
            }
            String sep = File.separator;
            String pathName = Environment.getExternalStorageDirectory() + sep + pgnDir + sep + pgnFile;
            savePGNToFile(pathName);
        }
    };

    new MaterialDialog.Builder(this).title(R.string.select_pgn_file_save).customView(content, true)
            .positiveText(android.R.string.ok).negativeText(R.string.cancel)
            .onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    savePGN.run();
                }
            }).onNegative(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                }
            }).show();

    fileNameView.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                savePGN.run();
                return true;
            }
            return false;
        }
    });
}

From source file:org.mdc.chess.MDChess.java

private void newNetworkEngineDialog() {
    View content = View.inflate(this, R.layout.create_network_engine, null);
    final EditText engineNameView = (EditText) content.findViewById(R.id.create_network_engine);
    final TextInputLayout engineNameWrapper = (TextInputLayout) content
            .findViewById(R.id.create_network_engine_wrapper);
    engineNameWrapper.setHint(content.getResources().getString(R.string.engine_name));
    engineNameView.setText("");
    final Runnable createEngine = new Runnable() {
        public void run() {
            String engineName = engineNameView.getText().toString();
            String sep = File.separator;
            String pathName = Environment.getExternalStorageDirectory() + sep + engineDir + sep + engineName;
            File file = new File(pathName);
            boolean nameOk = true;
            int errMsg = -1;
            if (engineName.contains("/")) {
                nameOk = false;/* www .j  a  v a  2 s  .com*/
                errMsg = R.string.slash_not_allowed;
            } else if (reservedEngineName(engineName) || file.exists()) {
                nameOk = false;
                errMsg = R.string.engine_name_in_use;
            }
            if (!nameOk) {
                Toast.makeText(getApplicationContext(), errMsg, Toast.LENGTH_LONG).show();
                networkEngineDialog();
                return;
            }
            networkEngineToConfig = pathName;
            networkEngineConfigDialog();
        }
    };
    new MaterialDialog.Builder(this).title(R.string.create_network_engine).customView(content, true)
            .positiveText(android.R.string.ok).negativeText(R.string.cancel)
            .onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    createEngine.run();
                }
            }).onNegative(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    networkEngineDialog();
                }
            }).show();

    engineNameView.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                createEngine.run();
                return true;
            }
            return false;
        }
    });
}