最近写了个项目,是使用webView写的,在网页加载的时候因为网速的原因,往往没有达到1秒即开的那种效果,所以添加了一个图片loading旋转的功能,告诉用户,APP正在加载中。
下面是xml布局代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main" tools:context=".MainActivity">
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/webView"
android:layout_alignParentBottom="true"
android:layout_marginBottom="0dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/loading1"
android:visibility="gone"
android:background="@color/gray"
android:alpha="0.3"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/loading"
android:src="@drawable/web_load"
android:scaleType="center"
android:visibility="gone"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="@dimen/fab_margin" />
</RelativeLayout>
使用RelativeLayout布局,只可以可以让控件层叠显示。首先创建一个ImageView,图片肯定是loading的那种,文中使用的是:
第二个Image使用背景颜色,透明度0.3,大致上布局完成,背景颜色的Image一定要在Loading图片的上面,这样才可以让Loading图片显示出来。
接着写代码:
Animation load_Anim = AnimationUtils.loadAnimation(mContext,R.anim.loading); load_Anim.setInterpolator(new LinearInterpolator()); 第一行的代码是加载一个动画,第二行是设置动画均匀;
R.anim.loading的源代码是:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:fromDegrees="0"
android:toDegrees="359"
android:duration="800"
android:repeatCount="-1"
android:pivotX="50%"
android:pivotY="50%" />
</set>
接着继续写JAVA的代码:
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
if(loading.getVisibility() == View.VISIBLE){
loading.clearAnimation();//一定要清楚动画,不然没办法隐藏image
loading.setVisibility(View.GONE);
loading1.setVisibility(View.GONE);
}
}else {
if (loading.getVisibility() == View.GONE){
loading.startAnimation(load_Anim);
loading.setVisibility(View.VISIBLE);
loading1.setVisibility(View.VISIBLE);
}
}
}
});
以上的代码就已实现页面加载的效果了。
下面是一张效果图:


