Android开发:在onCreate方法中两次调用setContentView

2014-11-24 10:53:32 ? 作者: ? 浏览: 0

为了实现欢迎界面,大家很自然地就会想到:在onCreate方法中,调用两次setContentView。是的,要调用两次setContentView,但怎么调用还是有点技巧,而不是简单地调用两次setContentView就可以解决问题的。下面,我们就用实际的例子来给予说明。


1. 在Eclipse中,先如下创建一个项目:



2. 将图片mm.png拷贝到项目的res/drawable-mdpi文件夹下,这个图片将用作欢迎界面。mm.png的图片是这样的:



3. 修改原项目的main.xml(假定它是真正的应用界面),使之如下:


< xml version="1.0"encoding="utf-8" >


"http://schemas.android.com/apk/res/android"


android:orientation="vertical"


android:layout_width="fill_parent"


android:layout_height="fill_parent"


>



android:layout_width="fill_parent"


android:layout_height="wrap_content"


android:textSize="40dip"


android:textColor="#FFFF00"


android:text="This is the real application interface!"


/>



android:layout_width="fill_parent"


android:layout_height="wrap_content"


android:text="OK"


/>




4. 再增加一个布局文件welcome.xml,用做欢迎界面。编辑该文件,使其内容如下:


< xml version="1.0"encoding="utf-8" >



xmlns:android="http://schemas.android.com/apk/res/android"


android:orientation="vertical"


android:layout_width="wrap_content"


android:layout_height="wrap_content">




android:layout_width="fill_parent"


android:layout_height="fill_parent"


android:scaleType="center"


android:src="@drawable/mm"


/>



很显然,这个欢迎界面就是显示步骤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); // 显示真正的应用界面


}


}


-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: