Android 自定义标题栏 显示网页加载进度的方法实例

前端技术 2023/09/06 Android

这阵子在做Lephone的适配,测试组提交一个bug:标题栏的文字较长时没有显示完全,其实这并不能算个bug,并且这个问题在以前其他机器也没有出现,只是说在Lephone的这个平台上显示得不怎么美观,因为联想将原生的标题栏UI进行了修改。修改的过程中遇到了一个难题,系统自带的那个标题栏进度总能够到达100%后渐退,但是我每次最后到100%那一段显示不全,尝试了用线程程序死了卡主了不说,还是一样的效果,后来同事一句话提醒了我用动画。确实是这样我猜系统的也是这样实现的,等进度到达100%后,用动画改变它的透明度就ok了。
实现的效果:标题栏显示网页标题并且滚动,并且用进度条显示网页的加载进度(重新自定义标题栏,lephone修改后的都带有一个返回按钮,并且标题文本和进度条是Frame布局的不怎么好看)。
1、首先定义一个RelativeLayout布局文件 broser_custom_title.xml (AlwaysMarqueeTextView这个类重写了TextView,实现一个跑马灯的效果,网上能够找到
 

复制代码 代码如下:

<?xml version=\"1.0\" encoding=\"utf-8\"?>
<RelativeLayout
  xmlns:android=\"http://schemas.android.com/apk/res/android\"
  android:layout_width=\"fill_parent\"
  android:layout_height=\"fill_parent\">

    <com.android.CustomTitleTest.AlwaysMarqueeTextView
            android:id=\"@+id/tvtitle\"
            android:layout_width=\"fill_parent\"
            android:layout_height=\"wrap_content\" android:focusableInTouchMode=\"true\"
            android:singleLine=\"true\" android:ellipsize=\"marquee\"
            android:focusable=\"false\" android:marqueeRepeatLimit=\"marquee_forever\"
            android:layout_centerVertical=\"true\"/>

    <ProgressBar android:id=\"@+id/pb\"
        android:layout_width=\"fill_parent\" android:layout_height=\"2sp\"
        style=\"?android:attr/progressBarStyleHorizontal\"
        android:visibility=\"gone\" android:layout_alignParentBottom=\"true\"
        ></ProgressBar>
</RelativeLayout>
 

2、继承WebChromeClient,重写onProgressChanged和onReceivedTitle事件(进度条加载完成后使用动画渐退)
 
复制代码 代码如下:

public class MyWebChromeClient extends WebChromeClient {

    private Activity activity;
    private ProgressBar pb;
    private TextView tvtitle;
    public MyWebChromeClient(Activity activity) {
        this.activity = activity;
    }
    Animation animation;
    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        pb=(ProgressBar)activity.findViewById(R.id.pb);
        pb.setMax(100);
        if(newProgress<100){
            if(pb.getVisibility()==View.GONE)
                pb.setVisibility(View.VISIBLE);
            pb.setProgress(newProgress);
        }else{
            pb.setProgress(100);
            animation=AnimationUtils.loadAnimation(activity, R.anim.animation);
            // 运行动画 animation
            pb.startAnimation(animation);
            // 将 spinner 的可见性设置为不可见状态
            pb.setVisibility(View.INVISIBLE);
        }

        super.onProgressChanged(view, newProgress);
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        tvtitle=(TextView)activity.findViewById(R.id.tvtitle);
        tvtitle.setText(title);
        super.onReceivedTitle(view, title);
    }

}
 

本文地址:https://www.stayed.cn/item/16701

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。