在项目中经常会遇到这样的场合,用户点击了一个界面后要提示等待加载,最后有可能显示加载失败,点击屏幕再重试加载。下面是该实例的代码:
layout: loading.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical|center_horizontal" android:background="#eee" android:id="@+id/loading_error_screen" > <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:id="@+id/loading_img" android:layout_centerHorizontal="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/loading_animator" /> <TextView android:text="正在加载中..." android:textSize="18sp" android:layout_below="@id/loading_img" android:layout_marginTop="12dp" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RelativeLayout> </RelativeLayout>
layout: loading_error.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical|center_horizontal" android:background="#eee" android:id="@+id/loading_error_screen" android:onClick="reloadContent" > <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:layout_centerHorizontal="true" android:id="@+id/loading_error_img" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/wb_request_loading_error" /> <TextView android:text="加载失败,请点击屏幕重试" android:textSize="18sp" android:layout_below="@id/loading_error_img" android:layout_marginTop="8dp" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RelativeLayout> </RelativeLayout>
Java:
package com.example.basicUI; import android.app.Activity; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.view.View; import android.widget.ImageView; /** * 作者:Heyiyong,2014年2月1日23:53:18 */ public class LoadingActivity extends Activity { private ImageView imageView; AnimationDrawable loadingDrawable; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //模拟加载数据 loadContent(); } /** * 加载数据 */ private void loadContent() { setContentView(R.layout.loding); //显示加载的那个动画 imageView = (ImageView) findViewById(R.id.loading_img); loadingDrawable = (AnimationDrawable) imageView.getBackground(); loadingDrawable.start(); new Thread(new Runnable() { @Override public void run() { //模拟加载数据 try { Thread.sleep(2200); } catch (InterruptedException e) { } runOnUiThread(new Runnable() { @Override public void run() { setContentView(R.layout.loading_error); } }); } }).start(); } /** * 加载失败的点击事件 */ public void reloadContent(View view) { loadContent(); } }