List of usage examples for android.view View LAYER_TYPE_SOFTWARE
int LAYER_TYPE_SOFTWARE
To view the source code for android.view View LAYER_TYPE_SOFTWARE.
Click Source Link
Indicates that the view has a software layer.
From source file:im.vector.adapters.VectorMediasViewerAdapter.java
@Override public Object instantiateItem(ViewGroup container, final int position) { View view = mLayoutInflater.inflate(R.layout.adapter_vector_medias_viewer, null, false); // hide the pie chart final PieFractionView pieFractionView = (PieFractionView) view.findViewById(R.id.media_slider_piechart); pieFractionView.setVisibility(View.GONE); final WebView imageWebView = (WebView) view.findViewById(R.id.media_slider_image_webview); final View videoLayout = view.findViewById(R.id.media_slider_videolayout); final ImageView thumbView = (ImageView) view.findViewById(R.id.media_slider_video_thumbnail); imageWebView.getSettings().setDisplayZoomControls(false); imageWebView.setOnLongClickListener(new View.OnLongClickListener() { @Override//from w w w. ja v a2 s . c o m public boolean onLongClick(View v) { VectorMediasViewerAdapter.this.onLongClick(); return true; } }); thumbView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { VectorMediasViewerAdapter.this.onLongClick(); return true; } }); // black background view.setBackgroundColor(0xFF000000); imageWebView.setBackgroundColor(0xFF000000); videoLayout.setBackgroundColor(0xFF000000); final SlidableMediaInfo mediaInfo = mMediasMessagesList.get(position); String mediaUrl = mediaInfo.mMediaUrl; if (mediaInfo.mMessageType.equals(Message.MSGTYPE_IMAGE)) { imageWebView.setVisibility(View.VISIBLE); imageWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); imageWebView.getSettings().setJavaScriptEnabled(true); imageWebView.getSettings().setLoadWithOverviewMode(true); imageWebView.getSettings().setUseWideViewPort(true); imageWebView.getSettings().setBuiltInZoomControls(true); videoLayout.setVisibility(View.GONE); final int rotationAngle = mediaInfo.mRotationAngle; final String mimeType = mediaInfo.mMimeType; File mediaFile = mMediasCache.mediaCacheFile(mediaUrl, mimeType); // is the high picture already downloaded ? if (null != mediaFile) { if (mHighResMediaIndex.indexOf(position) < 0) { mHighResMediaIndex.add(position); } } else { // try to retrieve the thumbnail mediaFile = mMediasCache.mediaCacheFile(mediaUrl, mMaxImageWidth, mMaxImageHeight, null); } // the thumbnail is not yet downloaded if (null == mediaFile) { // display nothing container.addView(view, 0); return view; } String mediaUri = "file://" + mediaFile.getPath(); String css = computeCss(mediaUri, mMaxImageWidth, mMaxImageHeight, rotationAngle); final String viewportContent = "width=640"; loadImage(imageWebView, Uri.parse(mediaUri), viewportContent, css); container.addView(view, 0); } else { loadVideo(position, view, mediaInfo.mThumbnailUrl, mediaUrl, mediaInfo.mMimeType); container.addView(view, 0); } // check if the media is downloading String downloadId = mMediasCache.downloadMedia(mContext, mSession.getHomeserverConfig(), mediaUrl, mediaInfo.mMimeType); if (null != downloadId) { pieFractionView.setVisibility(View.VISIBLE); pieFractionView.setFraction(mMediasCache.getProgressValueForDownloadId(downloadId)); pieFractionView.setTag(downloadId); mMediasCache.addDownloadListener(downloadId, new MXMediaDownloadListener() { @Override public void onDownloadError(String downloadId, JsonElement jsonElement) { pieFractionView.setVisibility(View.GONE); MatrixError error = JsonUtils.toMatrixError(jsonElement); if ((null != error) && error.isSupportedErrorCode()) { Toast.makeText(VectorMediasViewerAdapter.this.mContext, error.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } } @Override public void onDownloadProgress(String aDownloadId, DownloadStats stats) { if (aDownloadId.equals(pieFractionView.getTag())) { pieFractionView.setFraction(stats.mProgress); } } @Override public void onDownloadComplete(String aDownloadId) { if (aDownloadId.equals(pieFractionView.getTag())) { pieFractionView.setVisibility(View.GONE); } } }); } return view; }
From source file:ch.gianulli.flashcards.ui.Flashcard.java
private void expandButtonBar() { mButtonBarShowing = true;//from ww w . j a v a2 s. com mButtonBar.setVisibility(View.VISIBLE); mButtonBar.setAlpha(0.0f); final int startingHeight = mCardView.getHeight(); final ViewTreeObserver observer = mCardView.getViewTreeObserver(); observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { // We don't want to continue getting called for every listview drawing. if (observer.isAlive()) { observer.removeOnPreDrawListener(this); } final int endingHeight = mCardView.getHeight(); final int distance = endingHeight - startingHeight; mCardView.getLayoutParams().height = startingHeight; mCardView.requestLayout(); ValueAnimator heightAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(300); heightAnimator.setInterpolator(new DecelerateInterpolator()); heightAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animator) { Float value = (Float) animator.getAnimatedValue(); mCardView.getLayoutParams().height = (int) (value * distance + startingHeight); mCardView.requestLayout(); } }); heightAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mCardView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT; } }); mButtonBar.setLayerType(View.LAYER_TYPE_HARDWARE, null); ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(mButtonBar, "alpha", 0.0f, 1.0f); alphaAnimator.setInterpolator(new DecelerateInterpolator()); alphaAnimator.setDuration(300); alphaAnimator.setStartDelay(100); AnimatorSet set = new AnimatorSet(); set.playTogether(heightAnimator, alphaAnimator); set.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mButtonBar.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } }); set.start(); return false; } }); }
From source file:im.neon.adapters.VectorMediasViewerAdapter.java
@Override public Object instantiateItem(ViewGroup container, final int position) { View view = mLayoutInflater.inflate(R.layout.adapter_vector_medias_viewer, null, false); // hide the pie chart final PieFractionView pieFractionView = (PieFractionView) view.findViewById(R.id.media_slider_piechart); pieFractionView.setVisibility(View.GONE); final WebView imageWebView = (WebView) view.findViewById(R.id.media_slider_image_webview); final View videoLayout = view.findViewById(R.id.media_slider_videolayout); final ImageView thumbView = (ImageView) view.findViewById(R.id.media_slider_video_thumbnail); imageWebView.getSettings().setDisplayZoomControls(false); imageWebView.setOnLongClickListener(new View.OnLongClickListener() { @Override/*from w w w. j a va 2s . c o m*/ public boolean onLongClick(View v) { VectorMediasViewerAdapter.this.onLongClick(); return true; } }); thumbView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { VectorMediasViewerAdapter.this.onLongClick(); return true; } }); // black background view.setBackgroundColor(0xFF000000); imageWebView.setBackgroundColor(0xFF000000); videoLayout.setBackgroundColor(0xFF000000); final SlidableMediaInfo mediaInfo = mMediasMessagesList.get(position); String mediaUrl = mediaInfo.mMediaUrl; if (mediaInfo.mMessageType.equals(Message.MSGTYPE_IMAGE)) { imageWebView.setVisibility(View.VISIBLE); imageWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); imageWebView.getSettings().setJavaScriptEnabled(true); imageWebView.getSettings().setLoadWithOverviewMode(true); imageWebView.getSettings().setUseWideViewPort(true); imageWebView.getSettings().setBuiltInZoomControls(true); videoLayout.setVisibility(View.GONE); final int rotationAngle = mediaInfo.mRotationAngle; if (TextUtils.isEmpty(mediaInfo.mMimeType)) { mediaInfo.mMimeType = "image/jpeg"; } final String mimeType = mediaInfo.mMimeType; File mediaFile = mMediasCache.mediaCacheFile(mediaUrl, mimeType); // is the high picture already downloaded ? if (null != mediaFile) { if (mHighResMediaIndex.indexOf(position) < 0) { mHighResMediaIndex.add(position); } } else { // try to retrieve the thumbnail mediaFile = mMediasCache.mediaCacheFile(mediaUrl, mMaxImageWidth, mMaxImageHeight, null); } // the thumbnail is not yet downloaded if (null == mediaFile) { // display nothing container.addView(view, 0); return view; } String mediaUri = "file://" + mediaFile.getPath(); String css = computeCss(mediaUri, mMaxImageWidth, mMaxImageHeight, rotationAngle); final String viewportContent = "width=640"; loadImage(imageWebView, Uri.parse(mediaUri), viewportContent, css); container.addView(view, 0); } else { loadVideo(position, view, mediaInfo.mThumbnailUrl, mediaUrl, mediaInfo.mMimeType); container.addView(view, 0); } // check if the media is downloading String downloadId = mMediasCache.downloadMedia(mContext, mSession.getHomeserverConfig(), mediaUrl, mediaInfo.mMimeType, mediaInfo.mEncryptedFileInfo); if (null != downloadId) { pieFractionView.setVisibility(View.VISIBLE); pieFractionView.setFraction(mMediasCache.getProgressValueForDownloadId(downloadId)); pieFractionView.setTag(downloadId); mMediasCache.addDownloadListener(downloadId, new MXMediaDownloadListener() { @Override public void onDownloadError(String downloadId, JsonElement jsonElement) { pieFractionView.setVisibility(View.GONE); MatrixError error = JsonUtils.toMatrixError(jsonElement); if ((null != error) && error.isSupportedErrorCode()) { Toast.makeText(VectorMediasViewerAdapter.this.mContext, error.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } } @Override public void onDownloadProgress(String aDownloadId, DownloadStats stats) { if (aDownloadId.equals(pieFractionView.getTag())) { pieFractionView.setFraction(stats.mProgress); } } @Override public void onDownloadComplete(String aDownloadId) { if (aDownloadId.equals(pieFractionView.getTag())) { pieFractionView.setVisibility(View.GONE); } } }); } return view; }
From source file:com.playhaven.android.view.HTMLView.java
/** * Loads a url into the this webview, ensures * that load occurs on UI thread./*from ww w . ja va2 s . c om*/ * @param url to load */ public void load(final String url) { this.post(new Runnable() { @SuppressLint("InlinedApi") @Override public void run() { String fileUrl = null; try { Cache cache = new Cache(getContext()); File template = cache.getFile(new URL(url)); cache.close(); if (template != null && template.exists()) { fileUrl = "file:///" + template.getAbsolutePath(); } } catch (Exception e) { PlayHaven.e(e); } if (fileUrl != null && fileUrl.length() > 1) { PlayHaven.v("Loading from cache: %s.", fileUrl); HTMLView.this.loadUrl(fileUrl); } else { HTMLView.this.loadUrl(url); } setBackgroundColor(0x00000000); /** * @playhaven.apihack WebView has flickering & transparency issues when hardware acceleration is enabled. */ if (Build.VERSION.SDK_INT >= 11) { setLayerType(View.LAYER_TYPE_SOFTWARE, null); } } }); }
From source file:de.grobox.liberario.activities.MapActivity.java
private void showTrip(Trip trip) { int width = getResources().getDisplayMetrics().densityDpi / 32; // draw leg path first, so it is always at the bottom for (Leg leg : trip.legs) { // add path if it is missing if (leg.path == null) calculatePath(leg);//w w w .ja v a 2 s . c o m if (leg.path == null) continue; // draw leg path first, so it is always at the bottom Polyline polyline = new Polyline(); List<GeoPoint> geoPoints = new ArrayList<>(leg.path.size()); for (Point point : leg.path) { geoPoints.add(new GeoPoint(point.getLatAsDouble(), point.getLonAsDouble())); } polyline.setPoints(geoPoints); polyline.setWidth(width); if (leg instanceof Public) { Line line = ((Public) leg).line; polyline.setColor(getBackgroundColor(MarkerType.CHANGE, line)); if (line != null) polyline.setTitle(line.id); } else { polyline.setColor(getBackgroundColor(MarkerType.WALK, null)); polyline.setTitle(getString(R.string.walk)); } map.getOverlays().add(polyline); } // Now draw intermediate stops on top of path for (Leg leg : trip.legs) { if (leg instanceof Public) { Public public_leg = (Public) leg; if (public_leg.intermediateStops != null) { Drawable stop_drawable = getMarkerDrawable(MarkerType.STOP, public_leg.line); for (Stop stop : public_leg.intermediateStops) { if (stop.location != null) { markLocation(stop.location, stop_drawable); } } } } } // At last, draw the beginning, the end and the changing stations int i = 1; for (Leg leg : trip.legs) { // Draw public transportation stations if (leg instanceof Public) { Public public_leg = (Public) leg; // Draw first station or change station if (i == 1 || (i == 2 && trip.legs.get(0) instanceof Trip.Individual)) { markLocation(leg.departure, getMarkerDrawable(MarkerType.BEGIN, public_leg.line)); } else { markLocation(leg.departure, getMarkerDrawable(MarkerType.CHANGE, public_leg.line)); } // Draw final station only at the end or if end is walking if (i == trip.legs.size() || (i == trip.legs.size() - 1 && trip.legs.get(i) instanceof Trip.Individual)) { markLocation(leg.arrival, getMarkerDrawable(MarkerType.END, public_leg.line)); } } // Walking else if (leg instanceof Trip.Individual) { if (i != trip.legs.size() || trip.legs.size() == 1) { markLocation(leg.departure, getMarkerDrawable(MarkerType.WALK, null)); } // draw walking icon for arrival only at the end of the trip if (i == trip.legs.size()) { markLocation(leg.arrival, getMarkerDrawable(MarkerType.WALK, null)); } } i += 1; } // turn off hardware rendering to work around this issue: // https://github.com/MKergall/osmbonuspack/issues/168 map.setLayerType(View.LAYER_TYPE_SOFTWARE, null); }
From source file:com.mylikes.likes.etchasketch.Slate.java
@SuppressLint("NewApi") private void init() { // setWillNotCacheDrawing(true); // setDrawingCacheEnabled(false); mEmpty = true;//from w w w.jav a 2 s. com // setup brush bitmaps final ActivityManager am = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mMemClass = am.getLargeMemoryClass(); } else { mMemClass = am.getMemoryClass(); } mLowMem = (mMemClass <= 16); if (true || DEBUG) { Log.v(TAG, "Slate.init: memClass=" + mMemClass + (mLowMem ? " (LOW)" : "")); } final Resources res = getContext().getResources(); // mCircleBits = BitmapFactory.decodeResource(res, R.drawable.circle_1bpp); // if (mCircleBits == null) { Log.e(TAG, "SmoothStroker: Couldn't load circle bitmap"); } // mCircleBitsFrame = new Rect(0, 0, mCircleBits.getWidth(), mCircleBits.getHeight()); BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.ALPHA_8; if (mLowMem) { // let's see how this works in practice opts.inSampleSize = 4; } mAirbrushBits = BitmapFactory.decodeResource(res, R.drawable.airbrush_light, opts); if (mAirbrushBits == null) { Log.e(TAG, "SmoothStroker: Couldn't load airbrush bitmap"); } mAirbrushBitsFrame = new Rect(0, 0, mAirbrushBits.getWidth(), mAirbrushBits.getHeight()); //Log.v(TAG, "airbrush: " + mAirbrushBitsFrame.right + "x" + mAirbrushBitsFrame.bottom); mFountainPenBits = BitmapFactory.decodeResource(res, R.drawable.fountainpen, opts); if (mFountainPenBits == null) { Log.e(TAG, "SmoothStroker: Couldn't load fountainpen bitmap"); } mFountainPenBitsFrame = new Rect(0, 0, mFountainPenBits.getWidth(), mFountainPenBits.getHeight()); // set up individual strokers for each pointer mStrokes = new MarkersPlotter[MAX_POINTERS]; // TODO: don't bother unless hasSystemFeature(MULTITOUCH_DISTINCT) for (int i = 0; i < mStrokes.length; i++) { mStrokes[i] = new MarkersPlotter(); } mPressureCooker = new PressureCooker(getContext()); setFocusable(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (HWLAYER) { setLayerType(View.LAYER_TYPE_HARDWARE, null); } else if (SWLAYER) { setLayerType(View.LAYER_TYPE_SOFTWARE, null); } else { setLayerType(View.LAYER_TYPE_NONE, null); } } mWorkspacePaint = new Paint(); mWorkspacePaint.setColor(0x40606060); mBlitPaint = new Paint(); if (true) { mDebugPaints[0] = new Paint(); mDebugPaints[0].setStyle(Paint.Style.STROKE); mDebugPaints[0].setStrokeWidth(2.0f); mDebugPaints[0].setARGB(255, 0, 255, 255); mDebugPaints[1] = new Paint(mDebugPaints[0]); mDebugPaints[1].setARGB(255, 255, 0, 128); mDebugPaints[2] = new Paint(mDebugPaints[0]); mDebugPaints[2].setARGB(255, 0, 255, 0); mDebugPaints[3] = new Paint(mDebugPaints[0]); mDebugPaints[3].setARGB(255, 30, 30, 255); mDebugPaints[4] = new Paint(); mDebugPaints[4].setStyle(Paint.Style.FILL); mDebugPaints[4].setARGB(255, 128, 128, 128); } }
From source file:jahirfiquitiva.iconshowcase.fragments.DonationsFragment.java
/** * Build view for Flattr. see Flattr API for more information: * http://developers.flattr.net/button///from w ww .j av a 2s . 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) { try { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString))); } catch (ActivityNotFoundException e) { openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title, getString(R.string.donations__alert_dialog_no_browser)); } 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")) { WebView.HitTestResult result = view.getHitTestResult(); if (result != null && result.getType() > 0) { try { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } catch (ActivityNotFoundException e) { openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title, getString(R.string.donations__alert_dialog_no_browser)); } 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); } } }); // 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 TextView mFlattrUrlTextView = (TextView) getActivity().findViewById(R.id.donations__flattr_url); mFlattrUrlTextView.setText(flattrScheme + mFlattrUrl); 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='" + mFlattrProjectUrl + "' target='_blank'></a> <noscript><a href='" + flattrScheme + mFlattrUrl + "' 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"); // disable scroll on touch mFlattrWebview.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { // already handled (returns true) when moving return (motionEvent.getAction() == MotionEvent.ACTION_MOVE); } }); // 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:org.sufficientlysecure.donations.DonationsFragment.java
/** * Build view for Flattr. see Flattr API for more information: * http://developers.flattr.net/button//* w w w. j a v a 2 s . c om*/ */ @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) { try { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString))); } catch (ActivityNotFoundException e) { openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title, getString(R.string.donations__alert_dialog_no_browser)); } 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) { try { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } catch (ActivityNotFoundException e) { openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title, getString(R.string.donations__alert_dialog_no_browser)); } 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); } } }); // 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 mFlattrUrlTextView = (TextView) getActivity().findViewById(R.id.donations__flattr_url); mFlattrUrlTextView.setText(flattrScheme + mFlattrUrl); 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='" + mFlattrProjectUrl + "' target='_blank'></a> <noscript><a href='" + flattrScheme + mFlattrUrl + "' 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"); // disable scroll on touch mFlattrWebview.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { // already handled (returns true) when moving return (motionEvent.getAction() == MotionEvent.ACTION_MOVE); } }); // 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:org.wheelmap.android.fragment.POIDetailFragment.java
@TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setHardwareAccelerationOff() { // Turn off hardware acceleration here, or in manifest if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mMapView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); }//from www. ja v a 2 s. co m }
From source file:com.keylesspalace.tusky.ComposeActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String theme = preferences.getString("appTheme", ThemeUtils.APP_THEME_DEFAULT); if (theme.equals("black")) { setTheme(R.style.TuskyDialogActivityBlackTheme); }/* ww w .j a v a 2s .c o m*/ setContentView(R.layout.activity_compose); replyTextView = findViewById(R.id.composeReplyView); replyContentTextView = findViewById(R.id.composeReplyContentView); textEditor = findViewById(R.id.composeEditField); mediaPreviewBar = findViewById(R.id.compose_media_preview_bar); contentWarningBar = findViewById(R.id.composeContentWarningBar); contentWarningEditor = findViewById(R.id.composeContentWarningField); charactersLeft = findViewById(R.id.composeCharactersLeftView); tootButton = findViewById(R.id.composeTootButton); pickButton = findViewById(R.id.composeAddMediaButton); visibilityButton = findViewById(R.id.composeToggleVisibilityButton); contentWarningButton = findViewById(R.id.composeContentWarningButton); emojiButton = findViewById(R.id.composeEmojiButton); hideMediaToggle = findViewById(R.id.composeHideMediaButton); emojiView = findViewById(R.id.emojiView); emojiList = Collections.emptyList(); saveTootHelper = new SaveTootHelper(database.tootDao(), this); // Setup the toolbar. Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(null); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); Drawable closeIcon = AppCompatResources.getDrawable(this, R.drawable.ic_close_24dp); ThemeUtils.setDrawableTint(this, closeIcon, R.attr.compose_close_button_tint); actionBar.setHomeAsUpIndicator(closeIcon); } // setup the account image final AccountEntity activeAccount = accountManager.getActiveAccount(); if (activeAccount != null) { ImageView composeAvatar = findViewById(R.id.composeAvatar); if (TextUtils.isEmpty(activeAccount.getProfilePictureUrl())) { composeAvatar.setImageResource(R.drawable.avatar_default); } else { Picasso.with(this).load(activeAccount.getProfilePictureUrl()).error(R.drawable.avatar_default) .placeholder(R.drawable.avatar_default).into(composeAvatar); } composeAvatar.setContentDescription( getString(R.string.compose_active_account_description, activeAccount.getFullName())); mastodonApi.getInstance().enqueue(new Callback<Instance>() { @Override public void onResponse(@NonNull Call<Instance> call, @NonNull Response<Instance> response) { if (response.isSuccessful() && response.body().getMaxTootChars() != null) { maximumTootCharacters = response.body().getMaxTootChars(); updateVisibleCharactersLeft(); cacheInstanceMetadata(activeAccount); } } @Override public void onFailure(@NonNull Call<Instance> call, @NonNull Throwable t) { Log.w(TAG, "error loading instance data", t); loadCachedInstanceMetadata(activeAccount); } }); mastodonApi.getCustomEmojis().enqueue(new Callback<List<Emoji>>() { @Override public void onResponse(@NonNull Call<List<Emoji>> call, @NonNull Response<List<Emoji>> response) { emojiList = response.body(); setEmojiList(emojiList); cacheInstanceMetadata(activeAccount); } @Override public void onFailure(@NonNull Call<List<Emoji>> call, @NonNull Throwable t) { Log.w(TAG, "error loading custom emojis", t); loadCachedInstanceMetadata(activeAccount); } }); } else { // do not do anything when not logged in, activity will be finished in super.onCreate() anyway return; } composeOptionsView = findViewById(R.id.composeOptionsBottomSheet); composeOptionsView.setListener(this); composeOptionsBehavior = BottomSheetBehavior.from(composeOptionsView); composeOptionsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); addMediaBehavior = BottomSheetBehavior.from(findViewById(R.id.addMediaBottomSheet)); emojiBehavior = BottomSheetBehavior.from(emojiView); emojiView.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.HORIZONTAL, false)); enableButton(emojiButton, false, false); // Setup the interface buttons. tootButton.setOnClickListener(v -> onSendClicked()); pickButton.setOnClickListener(v -> openPickDialog()); visibilityButton.setOnClickListener(v -> showComposeOptions()); contentWarningButton.setOnClickListener(v -> onContentWarningChanged()); emojiButton.setOnClickListener(v -> showEmojis()); hideMediaToggle.setOnClickListener(v -> toggleHideMedia()); TextView actionPhotoTake = findViewById(R.id.action_photo_take); TextView actionPhotoPick = findViewById(R.id.action_photo_pick); int textColor = ThemeUtils.getColor(this, android.R.attr.textColorTertiary); Drawable cameraIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_alt).color(textColor) .sizeDp(18); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoTake, cameraIcon, null, null, null); Drawable imageIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_image).color(textColor).sizeDp(18); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoPick, imageIcon, null, null, null); actionPhotoTake.setOnClickListener(v -> initiateCameraApp()); actionPhotoPick.setOnClickListener(v -> onMediaPick()); thumbnailViewSize = getResources().getDimensionPixelSize(R.dimen.compose_media_preview_size); /* Initialise all the state, or restore it from a previous run, to determine a "starting" * state. */ Status.Visibility startingVisibility = Status.Visibility.UNKNOWN; boolean startingHideText; ArrayList<SavedQueuedMedia> savedMediaQueued = null; if (savedInstanceState != null) { startingVisibility = Status.Visibility .byNum(savedInstanceState.getInt("statusVisibility", Status.Visibility.PUBLIC.getNum())); statusMarkSensitive = savedInstanceState.getBoolean("statusMarkSensitive"); startingHideText = savedInstanceState.getBoolean("statusHideText"); // Keep these until everything needed to put them in the queue is finished initializing. savedMediaQueued = savedInstanceState.getParcelableArrayList("savedMediaQueued"); // These are for restoring an in-progress commit content operation. InputContentInfoCompat previousInputContentInfo = InputContentInfoCompat .wrap(savedInstanceState.getParcelable("commitContentInputContentInfo")); int previousFlags = savedInstanceState.getInt("commitContentFlags"); if (previousInputContentInfo != null) { onCommitContentInternal(previousInputContentInfo, previousFlags); } photoUploadUri = savedInstanceState.getParcelable("photoUploadUri"); } else { statusMarkSensitive = false; startingHideText = false; photoUploadUri = null; } /* If the composer is started up as a reply to another post, override the "starting" state * based on what the intent from the reply request passes. */ Intent intent = getIntent(); String[] mentionedUsernames = null; ArrayList<String> loadedDraftMediaUris = null; inReplyToId = null; if (intent != null) { if (startingVisibility == Status.Visibility.UNKNOWN) { Status.Visibility preferredVisibility = Status.Visibility.byString( preferences.getString("defaultPostPrivacy", Status.Visibility.PUBLIC.serverString())); Status.Visibility replyVisibility = Status.Visibility .byNum(intent.getIntExtra(REPLY_VISIBILITY_EXTRA, Status.Visibility.UNKNOWN.getNum())); startingVisibility = Status.Visibility .byNum(Math.max(preferredVisibility.getNum(), replyVisibility.getNum())); } inReplyToId = intent.getStringExtra(IN_REPLY_TO_ID_EXTRA); mentionedUsernames = intent.getStringArrayExtra(MENTIONED_USERNAMES_EXTRA); String contentWarning = intent.getStringExtra(CONTENT_WARNING_EXTRA); if (contentWarning != null) { startingHideText = !contentWarning.isEmpty(); if (startingHideText) { startingContentWarning = contentWarning; } } // If come from SavedTootActivity String savedTootText = intent.getStringExtra(SAVED_TOOT_TEXT_EXTRA); if (!TextUtils.isEmpty(savedTootText)) { startingText = savedTootText; textEditor.setText(savedTootText); } String savedJsonUrls = intent.getStringExtra(SAVED_JSON_URLS_EXTRA); if (!TextUtils.isEmpty(savedJsonUrls)) { // try to redo a list of media loadedDraftMediaUris = new Gson().fromJson(savedJsonUrls, new TypeToken<ArrayList<String>>() { }.getType()); } int savedTootUid = intent.getIntExtra(SAVED_TOOT_UID_EXTRA, 0); if (savedTootUid != 0) { this.savedTootUid = savedTootUid; } if (intent.hasExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA)) { replyTextView.setVisibility(View.VISIBLE); String username = intent.getStringExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA); replyTextView.setText(getString(R.string.replying_to, username)); Drawable arrowDownIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_down) .sizeDp(12); ThemeUtils.setDrawableTint(this, arrowDownIcon, android.R.attr.textColorTertiary); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowDownIcon, null); replyTextView.setOnClickListener(v -> { TransitionManager.beginDelayedTransition((ViewGroup) replyContentTextView.getParent()); if (replyContentTextView.getVisibility() != View.VISIBLE) { replyContentTextView.setVisibility(View.VISIBLE); Drawable arrowUpIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_up) .sizeDp(12); ThemeUtils.setDrawableTint(this, arrowUpIcon, android.R.attr.textColorTertiary); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowUpIcon, null); } else { replyContentTextView.setVisibility(View.GONE); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowDownIcon, null); } }); } if (intent.hasExtra(REPLYING_STATUS_CONTENT_EXTRA)) { replyContentTextView.setText(intent.getStringExtra(REPLYING_STATUS_CONTENT_EXTRA)); } } // After the starting state is finalised, the interface can be set to reflect this state. setStatusVisibility(startingVisibility); updateHideMediaToggle(); updateVisibleCharactersLeft(); // Setup the main text field. textEditor.setOnCommitContentListener(this); final int mentionColour = textEditor.getLinkTextColors().getDefaultColor(); SpanUtilsKt.highlightSpans(textEditor.getText(), mentionColour); textEditor.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable editable) { SpanUtilsKt.highlightSpans(editable, mentionColour); updateVisibleCharactersLeft(); } }); textEditor.setAdapter(new MentionAutoCompleteAdapter(this, R.layout.item_autocomplete, this)); textEditor.setTokenizer(new MentionTokenizer()); // Add any mentions to the text field when a reply is first composed. if (mentionedUsernames != null) { StringBuilder builder = new StringBuilder(); for (String name : mentionedUsernames) { builder.append('@'); builder.append(name); builder.append(' '); } startingText = builder.toString(); textEditor.setText(startingText); textEditor.setSelection(textEditor.length()); } // work around Android platform bug -> https://issuetracker.google.com/issues/67102093 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O || Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) { textEditor.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } // Initialise the content warning editor. contentWarningEditor.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { updateVisibleCharactersLeft(); } @Override public void afterTextChanged(Editable s) { } }); showContentWarning(startingHideText); if (startingContentWarning != null) { contentWarningEditor.setText(startingContentWarning); } // Initialise the empty media queue state. waitForMediaLatch = new CountUpDownLatch(); // These can only be added after everything affected by the media queue is initialized. if (!ListUtils.isEmpty(loadedDraftMediaUris)) { for (String uriString : loadedDraftMediaUris) { Uri uri = Uri.parse(uriString); long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri); pickMedia(uri, mediaSize); } } else if (savedMediaQueued != null) { for (SavedQueuedMedia item : savedMediaQueued) { Bitmap preview = MediaUtils.getImageThumbnail(getContentResolver(), item.uri, thumbnailViewSize); addMediaToQueue(item.id, item.type, preview, item.uri, item.mediaSize, item.readyStage, item.description); } } else if (intent != null && savedInstanceState == null) { /* Get incoming images being sent through a share action from another app. Only do this * when savedInstanceState is null, otherwise both the images from the intent and the * instance state will be re-queued. */ String type = intent.getType(); if (type != null) { if (type.startsWith("image/")) { List<Uri> uriList = new ArrayList<>(); if (intent.getAction() != null) { switch (intent.getAction()) { case Intent.ACTION_SEND: { Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (uri != null) { uriList.add(uri); } break; } case Intent.ACTION_SEND_MULTIPLE: { ArrayList<Uri> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (list != null) { for (Uri uri : list) { if (uri != null) { uriList.add(uri); } } } break; } } } for (Uri uri : uriList) { long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri); pickMedia(uri, mediaSize); } } else if (type.equals("text/plain")) { String action = intent.getAction(); if (action != null && action.equals(Intent.ACTION_SEND)) { String text = intent.getStringExtra(Intent.EXTRA_TEXT); if (text != null) { int start = Math.max(textEditor.getSelectionStart(), 0); int end = Math.max(textEditor.getSelectionEnd(), 0); int left = Math.min(start, end); int right = Math.max(start, end); textEditor.getText().replace(left, right, text, 0, text.length()); } } } } } textEditor.requestFocus(); }