Example usage for android.view View LAYER_TYPE_SOFTWARE

List of usage examples for android.view View LAYER_TYPE_SOFTWARE

Introduction

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

Prototype

int LAYER_TYPE_SOFTWARE

To view the source code for android.view View LAYER_TYPE_SOFTWARE.

Click Source Link

Document

Indicates that the view has a software layer.

Usage

From source file:com.propelics.pdfcreator.PdfcreatorModule.java

private void generateiTextPDFfunction(HashMap args) {
    Log.d(PROXY_NAME, "generateiTextPDFfunction()");

    String filename = "";
    TiUIView webview = null;//from   ww  w. j  a v a 2s .co  m
    int quality = 100;

    try {
        if (args.containsKey("filename")) {
            filename = (String) args.get("filename");
            Log.d(PROXY_NAME, "filename: " + filename);
        } else
            return;

        if (args.containsKey("webview")) {
            TiViewProxy viewProxy = (TiViewProxy) args.get("webview");
            webview = viewProxy.getOrCreateView();
            Log.d(PROXY_NAME, "webview: " + webview.toString());
        } else
            return;

        if (args.containsKey("quality")) {
            quality = TiConvert.toInt(args.get("quality"));
        }

        TiBaseFile file = TiFileFactory.createTitaniumFile(filename, true);
        Log.d(PROXY_NAME, "file full path: " + file.nativePath());

        OutputStream outputStream = file.getOutputStream();
        final int MARGIN = 0;
        final float PDF_WIDTH = PageSize.LETTER.getWidth() - MARGIN * 2; // A4: 595 //Letter: 612
        final float PDF_HEIGHT = PageSize.LETTER.getHeight() - MARGIN * 2; // A4: 842 //Letter: 792
        final int DEFAULT_VIEW_WIDTH = 980;
        final int DEFAULT_VIEW_HEIGHT = 1384;
        int viewWidth = DEFAULT_VIEW_WIDTH;
        int viewHeight = DEFAULT_VIEW_HEIGHT;

        Document pdfDocument = new Document(PageSize.LETTER, MARGIN, MARGIN, MARGIN, MARGIN);
        PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, outputStream);

        Log.d(PROXY_NAME, "PDF_WIDTH: " + PDF_WIDTH);
        Log.d(PROXY_NAME, "PDF_HEIGHT: " + PDF_HEIGHT);

        WebView view = (WebView) webview.getNativeView();

        if (TiApplication.isUIThread()) {

            viewWidth = view.capturePicture().getWidth();
            viewHeight = view.capturePicture().getHeight();

            if (viewWidth <= 0) {
                viewWidth = DEFAULT_VIEW_WIDTH;
            }

            if (viewHeight <= 0) {
                viewHeight = DEFAULT_VIEW_HEIGHT;
            }

        } else {
            Log.e(PROXY_NAME, "NO UI THREAD");
            viewWidth = DEFAULT_VIEW_WIDTH;
            viewHeight = DEFAULT_VIEW_HEIGHT;
        }

        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        Log.d(PROXY_NAME, "viewWidth: " + viewWidth);
        Log.d(PROXY_NAME, "viewHeight: " + viewHeight);

        float scaleFactorWidth = 1 / (viewWidth / PDF_WIDTH);
        float scaleFactorHeight = 1 / (viewHeight / PDF_HEIGHT);

        Log.d(PROXY_NAME, "scaleFactorWidth: " + scaleFactorWidth);
        Log.d(PROXY_NAME, "scaleFactorHeight: " + scaleFactorHeight);

        Bitmap viewBitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
        Canvas viewCanvas = new Canvas(viewBitmap);

        // Paint paintAntialias = new Paint();
        // paintAntialias.setAntiAlias(true);
        // paintAntialias.setFilterBitmap(true);

        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null) {
            bgDrawable.draw(viewCanvas);
        } else {
            viewCanvas.drawColor(Color.WHITE);
        }
        view.draw(viewCanvas);

        TiBaseFile pdfImg = createTempFile(filename);

        viewBitmap.compress(Bitmap.CompressFormat.PNG, quality, pdfImg.getOutputStream());

        FileInputStream pdfImgInputStream = new FileInputStream(pdfImg.getNativeFile());
        byte[] pdfImgBytes = IOUtils.toByteArray(pdfImgInputStream);
        pdfImgInputStream.close();

        pdfDocument.open();
        float yFactor = viewHeight * scaleFactorWidth;
        int pageNumber = 1;

        do {
            if (pageNumber > 1) {
                pdfDocument.newPage();
            }
            pageNumber++;
            yFactor -= PDF_HEIGHT;

            Image pageImage = Image.getInstance(pdfImgBytes, true);
            // Image pageImage = Image.getInstance(buffer.array());
            pageImage.scalePercent(scaleFactorWidth * 100);
            pageImage.setAbsolutePosition(0f, -yFactor);
            pdfDocument.add(pageImage);

            Log.d(PROXY_NAME, "yFactor: " + yFactor);
        } while (yFactor > 0);

        pdfDocument.close();

        sendCompleteEvent(filename);

    } catch (Exception exception) {
        sendErrorEvent(exception);
    }
}

From source file:chinanurse.cn.nurse.list.WaveView.java

private void initView() {
    setUpPaint();
    setUpPath();
    resetAnimator();

    mDropRect = new RectF();
    setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}

From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java

private void setupHardwareAcceleration() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        return;// w w w .  j a  va  2  s .com
    }

    if (isHardwareAccelerated()) {
        mMapView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    } else {
        mMapView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }
}

From source file:com.pablog178.pdfcreator.android.PdfcreatorModule.java

private void generateiTextPDFfunction(HashMap args) {
    if (args.containsKey("fileName")) {
        Object fileName = args.get("fileName");
        if (fileName instanceof String) {
            this.fileName = (String) fileName;
            Log.i(PROXY_NAME, "fileName: " + this.fileName);
        }/*from  w ww  .  j a  va 2  s .  c  o m*/
    } else
        return;

    if (args.containsKey("view")) {
        Object viewObject = args.get("view");
        if (viewObject instanceof TiViewProxy) {
            TiViewProxy viewProxy = (TiViewProxy) viewObject;
            this.view = viewProxy.getOrCreateView();
            if (this.view == null) {
                Log.e(PROXY_NAME, "NO VIEW was created!!");
                return;
            }
            Log.i(PROXY_NAME, "view: " + this.view.toString());
        }
    } else
        return;

    if (args.containsKey("quality")) {
        this.quality = TiConvert.toInt(args.get("quality"));
    }

    if (args.containsKey("pageSize")) {
        Object pageSize = args.get("pageSize");
        if (pageSize instanceof String) {
            if (pageSize.equals("letter")) {
                this.pageSize = PageSize.LETTER;
            } else if (pageSize.equals("A4")) {
                this.pageSize = PageSize.A4;
            } else {
                this.pageSize = PageSize.LETTER;
            }
        }
    }

    TiBaseFile file = TiFileFactory.createTitaniumFile(this.fileName, true);
    Log.i(PROXY_NAME, "file full path: " + file.nativePath());
    try {

        Resources appResources = app.getResources();
        OutputStream outputStream = file.getOutputStream();
        final int MARGIN = 0;
        final float PDF_WIDTH = this.pageSize.getWidth() - MARGIN * 2; // A4: 595 //Letter: 612
        final float PDF_HEIGHT = this.pageSize.getHeight() - MARGIN * 2; // A4: 842 //Letter: 792
        final int DEFAULT_VIEW_WIDTH = 980;
        final int DEFAULT_VIEW_HEIGHT = 1384;
        int viewWidth = DEFAULT_VIEW_WIDTH;
        int viewHeight = DEFAULT_VIEW_HEIGHT;

        Document pdfDocument = new Document(this.pageSize, MARGIN, MARGIN, MARGIN, MARGIN);
        PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, outputStream);

        Log.i(PROXY_NAME, "PDF_WIDTH: " + PDF_WIDTH);
        Log.i(PROXY_NAME, "PDF_HEIGHT: " + PDF_HEIGHT);

        WebView view = (WebView) this.view.getNativeView();

        if (TiApplication.isUIThread()) {

            viewWidth = view.capturePicture().getWidth();
            viewHeight = view.capturePicture().getHeight();

            if (viewWidth <= 0) {
                viewWidth = DEFAULT_VIEW_WIDTH;
            }

            if (viewHeight <= 0) {
                viewHeight = DEFAULT_VIEW_HEIGHT;
            }

        } else {
            Log.e(PROXY_NAME, "NO UI THREAD");
            viewWidth = DEFAULT_VIEW_WIDTH;
            viewHeight = DEFAULT_VIEW_HEIGHT;
        }

        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        Log.i(PROXY_NAME, "viewWidth: " + viewWidth);
        Log.i(PROXY_NAME, "viewHeight: " + viewHeight);

        float scaleFactorWidth = 1 / ((float) viewWidth / PDF_WIDTH);
        float scaleFactorHeight = 1 / ((float) viewHeight / PDF_HEIGHT);

        Log.i(PROXY_NAME, "scaleFactorWidth: " + scaleFactorWidth);
        Log.i(PROXY_NAME, "scaleFactorHeight: " + scaleFactorHeight);

        Bitmap viewBitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
        Canvas viewCanvas = new Canvas(viewBitmap);

        // Paint paintAntialias = new Paint();
        // paintAntialias.setAntiAlias(true);
        // paintAntialias.setFilterBitmap(true);

        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null) {
            bgDrawable.draw(viewCanvas);
        } else {
            viewCanvas.drawColor(Color.WHITE);
        }
        view.draw(viewCanvas);

        TiBaseFile pdfImg = createTempFile();

        // ByteArrayOutputStream stream = new ByteArrayOutputStream(32);
        // viewBitmap.compress(Bitmap.CompressFormat.JPEG, this.quality, stream);
        viewBitmap.compress(Bitmap.CompressFormat.JPEG, this.quality, pdfImg.getOutputStream());

        FileInputStream pdfImgInputStream = new FileInputStream(pdfImg.getNativeFile());
        byte[] pdfImgBytes = IOUtils.toByteArray(pdfImgInputStream);
        pdfImgInputStream.close();

        // ByteBuffer      buffer         = ByteBuffer.allocate(viewBitmap.getByteCount());
        // viewBitmap.copyPixelsToBuffer(buffer);

        pdfDocument.open();
        float yFactor = viewHeight * scaleFactorWidth;
        int pageNumber = 1;

        do {
            if (pageNumber > 1) {
                pdfDocument.newPage();
            }
            pageNumber++;
            yFactor -= PDF_HEIGHT;

            Image pageImage = Image.getInstance(pdfImgBytes, true);
            // Image pageImage = Image.getInstance(buffer.array());
            pageImage.scalePercent(scaleFactorWidth * 100);
            pageImage.setAbsolutePosition(0f, -yFactor);
            pdfDocument.add(pageImage);

            Log.i(PROXY_NAME, "yFactor: " + yFactor);
        } while (yFactor > 0);

        pdfDocument.close();

        sendCompleteEvent();

    } catch (Exception exception) {
        Log.e(PROXY_NAME, "Error: " + exception.toString());
        sendErrorEvent(exception.toString());
    }
}

From source file:eu.vranckaert.worktime.utils.donations.DonationsFragment.java

/**
 * Build view for Flattr. see Flattr API for more information:
 * http://developers.flattr.net/button//*  w w  w . j ava  2 s .c o  m*/
 */
@SuppressLint("SetJavaScriptEnabled")
@TargetApi(11)
private void buildFlattrView() {
    final FrameLayout mLoadingFrame;
    final WebView mFlattrWebview;

    mFlattrWebview = (WebView) getActivity().findViewById(R.id.donations__flattr_webview);
    mLoadingFrame = (FrameLayout) getActivity().findViewById(R.id.donations__loading_frame);

    // disable hardware acceleration for this webview to get transparent background working
    if (Build.VERSION.SDK_INT >= 11) {
        mFlattrWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // define own webview client to override loading behaviour
    mFlattrWebview.setWebViewClient(new WebViewClient() {
        /**
         * Open all links in browser, not in webview
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString)));

            return false;
        }

        /**
         * Links in the flattr iframe should load in the browser not in the iframe itself,
         * http:/
         * /stackoverflow.com/questions/5641626/how-to-get-webview-iframe-link-to-launch-the
         * -browser
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            if (url.contains("flattr")) {
                HitTestResult result = view.getHitTestResult();
                if (result != null && result.getType() > 0) {
                    view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    view.stopLoading();
                }
            }
        }

        /**
         * After loading is done, remove frame with progress circle
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            // remove loading frame, show webview
            if (mLoadingFrame.getVisibility() == View.VISIBLE) {
                mLoadingFrame.setVisibility(View.GONE);
                mFlattrWebview.setVisibility(View.VISIBLE);
            }
        }
    });

    // get flattr values from xml config
    String projectUrl = DonationsUtils.getResourceString(getActivity(), "donations__flattr_project_url");
    String flattrUrl = DonationsUtils.getResourceString(getActivity(), "donations__flattr_url");

    // make text white and background transparent
    String htmlStart = "<html> <head><style type='text/css'>*{color: #FFFFFF; background-color: transparent;}</style>";

    // https is not working in android 2.1 and 2.2
    String flattrScheme;
    if (Build.VERSION.SDK_INT >= 9) {
        flattrScheme = "https://";
    } else {
        flattrScheme = "http://";
    }

    // set url of flattr link
    mFlattrUrl = (TextView) getActivity().findViewById(R.id.donations__flattr_url);
    mFlattrUrl.setText(flattrScheme + flattrUrl);

    String flattrJavascript = "<script type='text/javascript'>" + "/* <![CDATA[ */" + "(function() {"
            + "var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];"
            + "s.type = 'text/javascript';" + "s.async = true;" + "s.src = '" + flattrScheme
            + "api.flattr.com/js/0.6/load.js?mode=auto';" + "t.parentNode.insertBefore(s, t);" + "})();"
            + "/* ]]> */" + "</script>";
    String htmlMiddle = "</head> <body> <div align='center'>";
    String flattrHtml = "<a class='FlattrButton' style='display:none;' href='" + projectUrl
            + "' target='_blank'></a> <noscript><a href='" + flattrScheme + flattrUrl
            + "' target='_blank'> <img src='" + flattrScheme
            + "api.flattr.com/button/flattr-badge-large.png' alt='Flattr this' title='Flattr this' border='0' /></a></noscript>";
    String htmlEnd = "</div> </body> </html>";

    String flattrCode = htmlStart + flattrJavascript + htmlMiddle + flattrHtml + htmlEnd;

    mFlattrWebview.getSettings().setJavaScriptEnabled(true);

    mFlattrWebview.loadData(flattrCode, "text/html", "utf-8");

    // make background of webview transparent
    // has to be called AFTER loadData
    // http://stackoverflow.com/questions/5003156/android-webview-style-background-colortransparent-ignored-on-android-2-2
    mFlattrWebview.setBackgroundColor(0x00000000);
}

From source file:ch.gianulli.flashcards.ui.Flashcard.java

public void turnCard() {
    if (mPreviousAnimation != null) {
        mPreviousAnimation.cancel();//from  ww w  .j ava2 s .  c o  m
        mPreviousAnimation = null;
    }

    AnimatorSet set = new AnimatorSet();

    mQuestion.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    mAnswer.setLayerType(View.LAYER_TYPE_HARDWARE, null);

    if (mQuestionShowing) {
        mQuestionShowing = false;

        mQuestion.setVisibility(View.VISIBLE);
        mQuestion.setAlpha(1.0f);
        mAnswer.setVisibility(View.VISIBLE);
        mAnswer.setAlpha(0.0f);

        ObjectAnimator questionAnim = ObjectAnimator.ofFloat(mQuestion, "alpha", 1.0f, 0.0f);
        questionAnim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mQuestion.setVisibility(View.GONE);
            }
        });

        ObjectAnimator answerAnim = ObjectAnimator.ofFloat(mAnswer, "alpha", 0.0f, 1.0f);

        set.playTogether(questionAnim, answerAnim);

        // Show button bar if necessary
        if (!mButtonBarShowing) {
            expandButtonBar();
        }
    } else {
        mQuestionShowing = true;

        mQuestion.setVisibility(View.VISIBLE);
        mQuestion.setAlpha(0.0f);
        mAnswer.setVisibility(View.VISIBLE);
        mAnswer.setAlpha(1.0f);

        ObjectAnimator questionAnim = ObjectAnimator.ofFloat(mQuestion, "alpha", 0.0f, 1.0f);

        ObjectAnimator answerAnim = ObjectAnimator.ofFloat(mAnswer, "alpha", 1.0f, 0.0f);
        answerAnim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mAnswer.setVisibility(View.GONE);
            }
        });

        set.playTogether(questionAnim, answerAnim);
    }

    set.setDuration(400);

    mPreviousAnimation = set;

    set.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            mQuestion.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            mAnswer.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            mPreviousAnimation = null;
        }
    });

    set.start();
}

From source file:com.appsimobile.appsii.module.weather.WeatherActivity.java

void showDrawable(Drawable drawable, boolean isImmediate) {
    mBackgroundImage.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    if (isImmediate) {
        int w = drawable.getIntrinsicWidth();
        int viewWidth = mBackgroundImage.getWidth();
        float factor = viewWidth / (float) w;
        int h = (int) (drawable.getIntrinsicHeight() * factor);
        drawable.setBounds(0, 0, w, h);/* w w w  .  ja v a2  s.  c o m*/
        mBackgroundImage.setImageDrawable(drawable);
    } else {
        Drawable current = mBackgroundImage.getDrawable();
        if (current == null)
            current = new ColorDrawable(Color.TRANSPARENT);
        TransitionDrawable transitionDrawable = new TransitionDrawable(new Drawable[] { current, drawable });
        transitionDrawable.setCrossFadeEnabled(true);
        mBackgroundImage.setImageDrawable(transitionDrawable);
        transitionDrawable.startTransition(500);
    }

}

From source file:com.kaltura.playersdk.PlayerViewController.java

/**
 * Build player URL and load it to player view
 * param iFrameUrl- String url//  w  w  w . j av a  2  s  .  c  om
 */
public void setComponents(String iframeUrl) {
    if (mWebView == null) {
        mWebView = new KControlsView(getContext());
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.clearCache(true);
        mWebView.clearHistory();
        mWebView.getSettings().setJavaScriptEnabled(true);
        //mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.setKControlsViewClient(this);
        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        mWebView.setBackgroundColor(0);
        mCurSec = 0;
        ViewGroup.LayoutParams currLP = getLayoutParams();
        LayoutParams wvLp = new LayoutParams(currLP.width, currLP.height);

        this.playerController = new KPlayerController(new KPlayer(mActivity), this);
        this.playerController.addPlayerToController(this);
        this.addView(mWebView, wvLp);
    }
    iframeUrl = RequestHandler.getIframeUrlWithNativeVersion(iframeUrl, this.getContext());
    if (mIframeUrl == null || !mIframeUrl.equals(iframeUrl)) {
        iframeUrl = iframeUrl + "&iframeembed=true";
        mIframeUrl = iframeUrl;
        mWebView.loadUrl(iframeUrl);
    }
}

From source file:com.albedinsky.android.ui.widget.BaseProgressBar.java

/**
 * Called from one of constructors of this view to perform its initialization.
 * <p>/*  w ww  .j a  va 2 s  .  c  o m*/
 * Initialization is done via parsing of the specified <var>attrs</var> set and obtaining for
 * this view specific data from it that can be used to configure this new view instance. The
 * specified <var>defStyleAttr</var> and <var>defStyleRes</var> are used to obtain default data
 * from the current theme provided by the specified <var>context</var>.
 */
@SuppressLint("NewApi")
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    this.mUiThreadId = Thread.currentThread().getId();
    // Use software layer that is required for proper drawing work of progress drawables.
    if (ProgressDrawable.REQUIRES_SOFTWARE_LAYER) {
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }
    onAttachDrawable();
    if (mDrawable == null) {
        throw new IllegalArgumentException("No progress drawable has been attached.");
    }
    /**
     * Process attributes.
     */
    final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Ui_ProgressBar,
            defStyleAttr, defStyleRes);
    if (typedArray != null) {
        this.processTintValues(context, typedArray);
        final int n = typedArray.getIndexCount();
        for (int i = 0; i < n; i++) {
            final int index = typedArray.getIndex(i);
            if (index == R.styleable.Ui_ProgressBar_android_max) {
                setMax(typedArray.getInt(index, getMax()));
            } else if (index == R.styleable.Ui_ProgressBar_android_progress) {
                setProgress(typedArray.getInt(index, mProgress));
            } else if (index == R.styleable.Ui_ProgressBar_uiColorProgress) {
                mDrawable.setColor(typedArray.getColor(index, mDrawable.getColor()));
            } else if (index == R.styleable.Ui_ProgressBar_uiColorsProgress) {
                final int colorsResId = typedArray.getResourceId(index, -1);
                if (colorsResId > 0 && !isInEditMode()) {
                    mDrawable.setColors(context.getResources().getIntArray(colorsResId));
                }
            } else if (index == R.styleable.Ui_ProgressBar_uiMultiColored) {
                mDrawable.setMultiColored(typedArray.getBoolean(index, mDrawable.isMultiColored()));
            } else if (index == R.styleable.Ui_ProgressBar_uiColorProgressBackground) {
                mDrawable.setBackgroundColor(typedArray.getInt(index, Color.TRANSPARENT));
            } else if (index == R.styleable.Ui_ProgressBar_android_thickness) {
                mDrawable.setThickness(typedArray.getDimensionPixelSize(index, 0));
            } else if (index == R.styleable.Ui_ProgressBar_uiRounded) {
                mDrawable.setRounded(!isInEditMode() && typedArray.getBoolean(index, mDrawable.isRounded()));
            } else if (index == R.styleable.Ui_ProgressBar_uiIndeterminateSpeed) {
                mDrawable.setIndeterminateSpeed(typedArray.getFloat(index, 1));
            }
        }
    }
    mDrawable.setInEditMode(isInEditMode());

    this.applyProgressTint();
    this.applyIndeterminateTint();
    this.applyProgressBackgroundTint();
}

From source file:com.taobao.weex.dom.transition.WXTransition.java

/**
 *  transform, opacity, backgroundcolor which not effect layout use android system animation in main thread.
 * *//*from ww w .  j a  v  a 2  s  . com*/
private void doPendingTransformAnimation(int token) {
    if (transformAnimator != null) {
        transformAnimator.cancel();
        transformAnimator = null;
    }
    if (transformPendingUpdates.size() == 0) {
        return;
    }
    final View taregtView = getTargetView();
    if (taregtView == null) {
        return;
    }
    List<PropertyValuesHolder> holders = new ArrayList<>(8);
    String transform = WXUtils.getString(transformPendingUpdates.remove(Constants.Name.TRANSFORM), null);
    if (!TextUtils.isEmpty(transform)) {
        Map<Property<View, Float>, Float> properties = TransformParser.parseTransForm(transform,
                (int) domObject.getLayoutWidth(), (int) domObject.getLayoutHeight(),
                domObject.getViewPortWidth());
        PropertyValuesHolder[] transformHolders = TransformParser.toHolders(properties);
        for (PropertyValuesHolder holder : transformHolders) {
            holders.add(holder);
        }
        synchronized (targetStyles) {
            targetStyles.put(Constants.Name.TRANSFORM, transform);
        }
    }

    for (String property : properties) {
        if (!TRANSFORM_PROPERTIES.contains(property)) {
            continue;
        }
        if (!transformPendingUpdates.containsKey(property)) {
            continue;
        }
        Object value = transformPendingUpdates.remove(property);
        synchronized (targetStyles) {
            targetStyles.put(property, value);
        }
        switch (property) {
        case Constants.Name.OPACITY: {
            holders.add(PropertyValuesHolder.ofFloat(View.ALPHA, taregtView.getAlpha(),
                    WXUtils.getFloat(value, 1.0f)));
            taregtView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); //hardware or none has bug on some platform
        }
            break;
        case Constants.Name.BACKGROUND_COLOR: {
            int fromColor = WXResourceUtils
                    .getColor(WXUtils.getString(domObject.getStyles().getBackgroundColor(), null), 0);
            int toColor = WXResourceUtils.getColor(WXUtils.getString(value, null), 0);
            if (WXViewUtils.getBorderDrawable(taregtView) != null) {
                fromColor = WXViewUtils.getBorderDrawable(taregtView).getColor();
            } else if (taregtView.getBackground() instanceof ColorDrawable) {
                fromColor = ((ColorDrawable) taregtView.getBackground()).getColor();
            }
            holders.add(PropertyValuesHolder.ofObject(new BackgroundColorProperty(), new ArgbEvaluator(),
                    fromColor, toColor));
        }
            break;
        default:
            break;
        }
    }

    if (token == lockToken.get()) {
        transformPendingUpdates.clear();
    }
    transformAnimator = ObjectAnimator.ofPropertyValuesHolder(taregtView,
            holders.toArray(new PropertyValuesHolder[holders.size()]));
    transformAnimator.setDuration((long) duration);
    if ((long) delay > 0) {
        transformAnimator.setStartDelay((long) delay);
    }
    if (interpolator != null) {
        transformAnimator.setInterpolator(interpolator);
    }
    transformAnimator.addListener(new AnimatorListenerAdapter() {
        boolean hasCancel = false;

        @Override
        public void onAnimationCancel(Animator animation) {
            super.onAnimationCancel(animation);
            hasCancel = true;
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            if (hasCancel) {
                return;
            }
            super.onAnimationEnd(animation);
            WXTransition.this.onTransitionAnimationEnd();
            if (WXEnvironment.isApkDebugable()) {
                WXLogUtils.d("WXTransition transform onTransitionAnimationEnd " + domObject.getRef());
            }
        }
    });
    transformAnimator.start();
}