先看效果图:
布局文件代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="@drawable/bg">
<TextView
android:id="@+id/tv_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:textSize="60dp"
android:text="@string/title"
android:textScaleX="1.23"
android:textColor="#333333"
android:gravity="center_horizontal"
/>
<wht.android.loading.LoadingView
android:layout_gravity="center_horizontal" android:layout_height="wrap_content"
android:id="@+id/main_imageview" android:src="@drawable/loader_frame_1"
android:layout_marginTop="190dp" android:layout_width="wrap_content"
></wht.android.loading.LoadingView>
<TextView
android:id="@+id/tv_load"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/loadStr"
android:layout_marginTop="10dip"
android:textColor="#666666"
android:layout_gravity="center_horizontal"
android:textSize="13sp"
/>
</LinearLayout>
要点一:自定义字体
在assets文件夹下新建一个fonts文件夹,然后将自己的字体文件(.ttf)拷贝到fonts文件夹中(这里是一些我收集的一些比较好的字体),然后再需要的地方使用一下代码即可。
//自定义字体
Typeface tf1 = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Thin.ttf");
Typeface tf2 = Typeface.createFromAsset(getAssets(), "fonts/Roboto-BoldCondensed.ttf");
loadView.setTypeface(tf1);
titleView.setTypeface(tf2);
要点二:加载动画的实现
在线程中每隔0.4秒执行postInvalidate()更新view,会自动调用onDraw(Canvas canvas)方法来设置imageView。
以下用别人代码作为示例,我添加了一些注释。
public class LoadingView extends ImageView implements Runnable{
private boolean isStop = false; //动画停止标志
private int[] imageIds;
private int index = 0;
private int length = 1;
public LoadingView(Context context)
{
this(context, null);
}
public LoadingView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public void setImageIds(int[] imageId)
{
this.imageIds = imageId;
if(imageIds != null && imageIds.length > 0)
{
length = imageIds.length;
}
}
/**
* 当View离开当前窗口时调用。当按下返回键时可以正常调用该方法,但是当点击Home键退出时则无法正常调用。
*/
@Override
protected void onDetachedFromWindow()
{
super.onDetachedFromWindow();
isStop = true;
}
/**
* 在view刷新,绘制时调用,调用invalidate或者postInvalidate方法就会执行onDraw方法
*/
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
if(imageIds != null && imageIds.length > 0)
{
this.setImageResource(imageIds[index]);
}
}
@Override
public void run()
{
while(!isStop)
{
index = ++index % length;
postInvalidate();//更新View,调用onDraw方法
try
{
Thread.sleep(400);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
/**
* 启动动画
*/
public void startAnim()
{
new Thread(this).start();
}
}
注:源代码打包下载,请点击 这里。