首页 / 操作系统 / Linux / Android开发:在onCreate方法中两次调用setContentView
在做Android开发的时候,有时候需要在一个Activity的里面调用两次setContentView方法。比如在应用启动的时候,开始显示欢迎界面,在显示欢迎界面的同时,进行后台数据的处理,等到后台数据准备好了,才显示真正的应用界面。这样的做法不会让使用者有突兀的感觉。反之,应用已启动就显示真正的应用界面,但在后续的操作需要准备数据的时候,假定是5秒钟,那么在这5秒钟内使用者将无法使用该应用,这样用户界面显然是不够友好的。为了实现欢迎界面,大家很自然地就会想到:在onCreate方法中,调用两次setContentView。是的,要调用两次setContentView,但怎么调用还是有点技巧,而不是简单地调用两次setContentView就可以解决问题的。下面,我们就用实际的例子来给予说明。1. 在Eclipse中,先如下创建一个项目:2. 将图片mm.png拷贝到项目的res/drawable-mdpi文件夹下,这个图片将用作欢迎界面。mm.png的图片是这样的:3. 修改原项目的main.xml(假定它是真正的应用界面),使之如下:<?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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="40dip" android:textColor="#FFFF00" android:text="This is the real application interface!" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="OK" /></LinearLayout> 4. 再增加一个布局文件welcome.xml,用做欢迎界面。编辑该文件,使其内容如下:<?xml version="1.0"encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:layout_width="fill_parent" android:layout_height="fill_parent" android:scaleType="center" android:src="@drawable/mm" /></LinearLayout>很显然,这个欢迎界面就是显示步骤2增加的图片mm.png 5. 下面来完善WelcomeActivity.java的代码,如果我们像下面这样直接写:package com.pat.welcome; import android.app.Activity;import android.os.Bundle; public class WelcomeActivity extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.main); // 把这一句改为下面一句,用以显示欢迎界面 setContentView(R.layout.welcome); // 下面是模拟数据处理需要5秒钟的时间 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } setContentView(R.layout.main); // 显示真正的应用界面 }}