android 监听webView滑动距离和标题栏颜色渐变

重写webView之 X5WebView

 

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AbsoluteLayout;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.yuanxin.clan.R;
import com.yuanxin.clan.core.app.UserNative;
import com.yuanxin.clan.core.company.utils.MyWebChromeClient;
import com.yuanxin.clan.core.util.FastJsonUtils;
import com.yuanxin.clan.mvp.entity.UserAgentParam;
import com.yuanxin.clan.mvp.utils.CommonString;import java.util.ArrayList;
import java.util.List;public class X5WebView extends WebView {private ProgressBar progressbar;  //进度条private int progressHeight = 10;  //进度条的高度,默认10pxTextView title;private ActionMode mActionMode;private List<String> mActionList = new ArrayList<>();private WebViewClient client = new WebViewClient() {/*** 防止加载网页时调起系统浏览器*/public boolean shouldOverrideUrlLoading(WebView view, String url) {view.loadUrl(url);return true;}// 重写 WebViewClient  的  shouldInterceptRequest ()// API 21 以下用shouldInterceptRequest(WebView view, String url)// API 21 以上用shouldInterceptRequest(WebView view, WebResourceRequest request)// 下面会详细说明// API 21 以下用shouldInterceptRequest(WebView view, String url)
//        @Override
//        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
//            if (url.contains("jquery.js"))
//       {
//          String localPath = url.replaceFirst("^http.*[tag]\\]", "");
//          try
//          {
//             InputStream is = getContext().getAssets().open(localPath);
//             String mimeType = "text/javascript";
//             if (localPath.endsWith("css"))
//             {
//                mimeType = "text/css";
//             }
//             return new WebResourceResponse(mimeType, "UTF-8", is);
//          }
//          catch (Exception e)
//          {
//             e.printStackTrace();
//          }
//       }
//            return super.shouldInterceptRequest(view, url);
//        }
//
//
//        // API 21 以上用shouldInterceptRequest(WebView view, WebResourceRequest request)
//        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
//        @Override
//        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
//            String url = request.getUrl().toString();
//            if (url.contains("[tag]"))
//            {
//                String localPath = url.replaceFirst("^http.*[tag]\\]", "");
//                try
//                {
//                    InputStream is = getContext().getAssets().open(localPath);
//                    String mimeType = "text/javascript";
//                    if (localPath.endsWith("css"))
//                    {
//                        mimeType = "text/css";
//                    }
//                    return new WebResourceResponse(mimeType, "UTF-8", is);
//                }
//                catch (Exception e)
//                {
//                    e.printStackTrace();
//                }
//            }
//            return super.shouldInterceptRequest(view, request);
//        }};public OnScrollListener listener;/*** This is called in response to an internal scroll in this view (i.e., the* view scrolled its own contents). This is typically as a result of* {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been* called.** @param l Current horizontal scroll origin.* @param t Current vertical scroll origin.* @param oldl Previous horizontal scroll origin.* @param oldt Previous vertical scroll origin.*/@Overrideprotected void onScrollChanged(int l, int t, int oldl, int oldt) {super.onScrollChanged(l, t, oldl, oldt);if (listener != null){if (t - oldt <= 2){listener.onScrollDown();}if(oldt - t >= 2) {listener.onScrollUp();}listener.scrollHeight(t);}}public void setListener(OnScrollListener listener){this.listener = listener;}public interface OnScrollListener{void onScrollUp();//上滑void onScrollDown();//下滑void scrollHeight(int h);}//这两个方法会在用户长按选择web文本时,在弹出菜单前被调用。@Overridepublic ActionMode startActionMode(ActionMode.Callback callback) {ActionMode actionMode = startActionMode(callback);Log.e("hxw", actionMode.toString());return resolveActionMode(actionMode);}@Overridepublic ActionMode startActionMode(ActionMode.Callback callback, int type) {ActionMode actionMode = startActionMode(callback, type);Log.e("hxw", actionMode.toString() + " " + type);return resolveActionMode(actionMode);}//处理item,处理点击private ActionMode resolveActionMode(ActionMode actionMode) {if (actionMode != null) {final Menu menu = actionMode.getMenu();mActionMode = actionMode;menu.clear();Log.e("hxw", mActionList.toString());for (int i = 0; i < mActionList.size(); i++) {menu.add(mActionList.get(i));}for (int i = 0; i < menu.size(); i++) {MenuItem menuItem = menu.getItem(i);menuItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {@Overridepublic boolean onMenuItemClick(MenuItem item) {// getSelectedData((String) item.getTitle());// releaseAction();return true;}});}}mActionMode = actionMode;return actionMode;}//设置弹出action列表public void setActionList(List<String> actionList) {mActionList = actionList;}@SuppressLint("SetJavaScriptEnabled")public X5WebView(Context arg0, AttributeSet arg1) {super(arg0, arg1);initWebViewSettings(arg0);this.setWebViewClient(client);this.setWebChromeClient(new MyWebChromeClient(arg0, progressbar));// this.setWebChromeClient(chromeClient);// WebStorage webStorage = WebStorage.getInstance();this.getView().setClickable(true);}public void setProgressbarDrawable(Drawable d) {progressbar.setProgressDrawable(d);}private void initWebViewSettings(Context context) {//创建进度条progressbar = new ProgressBar(context, null,android.R.attr.progressBarStyleHorizontal);//设置加载进度条的高度progressbar.setLayoutParams(new AbsoluteLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, progressHeight, 0, 0));Drawable drawable = context.getResources().getDrawable(R.drawable.progressbar_blue);progressbar.setProgressDrawable(drawable);//添加进度到WebViewaddView(progressbar);WebSettings webSetting = this.getSettings();webSetting.setJavaScriptEnabled(true);webSetting.setJavaScriptCanOpenWindowsAutomatically(true);webSetting.setAllowFileAccess(true);webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);webSetting.setSupportZoom(true);webSetting.setBuiltInZoomControls(true);webSetting.setUseWideViewPort(true);webSetting.setSupportMultipleWindows(true);// webSetting.setLoadWithOverviewMode(true);webSetting.setAppCacheEnabled(false);// webSetting.setDatabaseEnabled(true);webSetting.setDomStorageEnabled(true);webSetting.setGeolocationEnabled(true);webSetting.setAppCacheMaxSize(Long.MAX_VALUE);webSetting.setTextSize(WebSettings.TextSize.NORMAL);// webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);// webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);webSetting.setDisplayZoomControls(false);this.setWebContentsDebuggingEnabled(true);String ua = webSetting.getUserAgentString();UserAgentParam up = new UserAgentParam(CommonString.appTag, UserNative.getId(), UserNative.getName(), UserNative.getPhone(), UserNative.getPwd(), UserNative.getEpId());webSetting.setUserAgent(ua + "&" + FastJsonUtils.toJSONString(up));webSetting.setLoadsImagesAutomatically(true);Log.e("hxw", webSetting.getUserAgentString());// this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extension// settings 的设计}// @Override
// protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
//    boolean ret = super.drawChild(canvas, child, drawingTime);
//    canvas.save();
//    Paint paint = new Paint();
//    paint.setColor(0x7fff0000);
//    paint.setTextSize(24.f);
//    paint.setAntiAlias(true);
//    if (getX5WebViewExtension() != null) {
//       canvas.drawText(this.getContext().getPackageName() + "-pid:"
//             + android.os.Process.myPid(), 10, 50, paint);
//       canvas.drawText(
//             "X5  Core:" + QbSdk.getTbsVersion(this.getContext()), 10,
//             100, paint);
//    } else {
//       canvas.drawText(this.getContext().getPackageName() + "-pid:"
//             + android.os.Process.myPid(), 10, 50, paint);
//       canvas.drawText("Sys Core", 10, 100, paint);
//    }
//    canvas.drawText(Build.MANUFACTURER, 10, 150, paint);
//    canvas.drawText(Build.MODEL, 10, 200, paint);
//    canvas.restore();
//    return ret;
// }/*public X5WebView(Context arg0) {super(arg0);setBackgroundColor(85621);}*/
}

 

 

 

webview 监听滑动距离

 

 

        mWebview.setListener(new X5WebView.OnScrollListener() {@Overridepublic void onScrollUp() {Logger.e("up");}@Overridepublic void onScrollDown() {Logger.e("down");}@Overridepublic void scrollHeight(int h) {if (h > 0) {headLayout.setBackgroundResource(R.color.epblueyl);//标题栏颜色渐变}float f = (h + 0f) / 450;//滑动距离450pxif (f > 1) {f = 1f;}if (f < 0) {f = 0;}
//                headLayout.setAlpha(f*1);headLayout.setBackgroundColor(ColorUtils.changeAlpha(ContextCompat.getColor(YxServiceActivity.this, R.color.epblueyl),(int)(f * 1 * 0xff)));}});

通用标题栏渐变色demo:https://blog.csdn.net/meixi_android/article/details/78124913

 

实现效果:渐变显示

 

demo链接:https://download.csdn.net/download/meixi_android/10966003

demo云盘链接:https://pan.baidu.com/s/1bNGSzYitvXTUk4x_3PgPWw

云盘密码:回复QQ——1085220040

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/415896.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mpvue 从零开始 女友拉黑了我 5 不在以下request 合法域名列表中,请参考文档

上一篇&#xff0c;才调通了接口&#xff0c;试了几次&#xff0c;都成功&#xff0c;突然&#xff0c;微信报错了。 VM6239:1 https://www.easy-mock.com 不在以下 request 合法域名列表中&#xff0c;请参考文档&#xff1a;https://mp.weixin.qq.com/debug/wxadoc/dev/api…

Javascript与C#中使用正则表达式

JavaScript RegExp 对象 新建一个RegExp对象 new RegExp(pattern,[attributes]) 注&#xff1a; \d需要使用[0-9]来代替 参数 参数 pattern 是一个字符串&#xff0c;指定了正则表达式的模式或其他正则表达式。 参数 attributes 是一个可选的字符串&#xff0c;包含…

Windows 不能在 本地计算机 启动 SQL Server 服务 错误代码126

Windows 不能在 本地计算机 启动 SQL Server 服务 错误代码126 在使用SQL2005&#xff08;或2008&#xff09;是可能会遇到错误提示&#xff1a; “Windows 不能在 本地计算机 启动 SQL Server 。 有关更多信息&#xff0c;查阅系统事件日志。如果这是非 Microsoft 服务&…

android Calendar使用 年月日时分秒

int myhour0;int mymin0;int mymonth0;int myday0;int twoday0;try {final Calendar c Calendar.getInstance();c.setTimeZone(TimeZone.getTimeZone("GMT8:00"));//获取当前时间的年月日String mDay String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份…

微信小程序报错 .wxss 无法找到

使用mpvue 报错&#xff0c;无法找到wxss文件&#xff0c;解决方法&#xff0c;删除dist目录里面的内容。重重新编译&#xff0c;解决问题。

《结对-贪吃蛇-设计文档》

设计人员&#xff1a; 张晓亮、李国峰 环境搭建&#xff1a; 本系统有Java语言编写。需要在本地搭建Java运行环境。1&#xff09;下载JDK&#xff08;官网下载1.7以上版本&#xff09;2&#xff09;下载eclipseIDE开发软件。本人是Mac系统所以不需要额外配置环境变量。 可行性分…

FileZilla Server 搭建FTP服务器

FileZilla Server 搭建FTP服务器 1. 背景:在免费&#xff08;此类工具免费者很多&#xff09;中&#xff0c;我的选择是FileZilla&#xff0c;因为它小巧、非常强大、也比较易用&#xff0c;且为开源软件&#xff0c;发展前景不错。用户也比较多&#xff0c;有问题容易解决。  …

mpvue 从零开始 女友的收纳盒 6 mpvue-entry入口管理

给女友买了很多化妆品&#xff0c;琳琅满目&#xff0c;傻傻分不清&#xff0c;需要有一个魔法工具&#xff0c;自动将化妆品分类到收纳盒对应的格子里面&#xff0c;这就是mpvue-entry要做的事情。 1、安装mpvue-entry yarn add mpvue-entry2、在webpack.base.conf.js中进行配…

android Intent传递对象,startActivityForResult使用, setResult(RESULT_OK)使用,getArguments(),

Bundle bundle this.getIntent().getExtras(); if(bundle !null){ Fragment、getArguments() 传 public static DriverHistoryFragment getInstance(String tag) {Bundle bundle new Bundle();bundle.putString(TAG, tag);DriverHistoryFragment fragment new DriverHist…

64位Windows2003 Enterprise sp2 上64位Oracle10.2.0.1升级到Oracle10.2.0.3具体步骤

64位Windows2003 Enterprise sp2 上64位Oracle10.2.0.1升级到Oracle10.2.0.3具体步骤 错误描述&#xff1a;64位的Oracle10.2.0.1版本在64位Windows2003 Enterprise sp2上有一个很严重的bug&#xff0c;Oracle进程的先耗尽系统的所有虚拟内存&#xff0c;然后耗尽系统的真实内存…

mac安装mongodb

1、去官网进行下载mongodb官网 2、将下载好的压缩包解压&#xff0c;将解压出的文件夹下的内容全部复制到新的路径下。 cp -r mongodb-osx-x86_64-4.0.4 /usr/local/mongodb把 MongoDB 的二进制命令文件目录&#xff08;安装目录/bin&#xff09;添加到 PATH 路径中&#xff…

android 圆形头像,自定义圆形ImageView

<!--头像--><RelativeLayoutandroid:id"id/ll_petInfo"android:layout_width"50dp"android:layout_height"50dp"android:layout_marginBottom"10dp"android:layout_marginTop"1dp"android:gravity"center&quo…

PHP-Windows下搭建PHP-MSF环境【原创】

环境:   Windows7 64位   php-7.0.19   php-swoole-1.9.15   php-yac-2.0.2   php-redis-3.1.2   php-mongodb-1.2.10 遇坑: Cygwin: 不能默认使用 Windows 自带的 mingw git&#xff0c;否则报"fatal: Unable to create temporary file: Result too large&qu…

ORACLE SGA问题分析

&#xfeff;&#xfeff;&#xfeff;&#xfeff;ORACLE SGA问题分析 select sum(value)/1024/1024 from v$sga; --查看SGA总大小 select current_size from v$buffer_pool; --查看当前高速缓冲池大小 select pool, sum(bytes)/1024/1024 Mbytes from v$sgastat group by p…

adb 启动命令,pc启动两个微信,INSTALL_FAILED_CONFLICTING_PROVIDER

adb kill-server 在关闭adb服务后&#xff0c;要使用如下的命令启动adb服务。 adb start-server 电脑启动两个微信 进入安装目录下。cmd The application could not be installed: INSTALL_FAILED_CONFLICTING_PROVIDER 错误 解决方法 1所示就是冲突的authorities.2所示…

微信小程序登录 更新中

小程序登录文档地址 0、下面的时序图必须要掌握。 1、获取code&#xff0c;向开发者服务器发送 2、开发者服务器根据code获取 需要准备appid、appsecret、code 调用接口文档code2Session const result await superagent.get(https://api.weixin.qq.com/sns/jscode2session).…