两个页面
目标人群:没有基础的安卓初学者
知识点:Activity之间的跳转
目标:通过点击页面的按钮来跳转至一个新的页面
简介
本章会简单的介绍如何通过点击页面上的按钮来跳转至一个新的页面
本章需要少量Java语法知识
正文
1.创建一个新的布局文件activity_hello.xml,内容如下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="你好"
android:id="@+id/textView1" />
</LinearLayout>
2.activity_main.xml的代码修改为如下所示
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下一页"
android:onClick="goHello"
android:id="@+id/button" />
</LinearLayout>
我们为这个Button添加了一个值为goHello的android:onClick属性,当按钮被点击时,将会跳转至新的页面。
3.创建一个名为HelloActivity.java的文件,内容如下所示。
package cnlive.com.myapplication;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by Duan on 2月13日.
*/
public class HelloActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
}
}
- 本页面的所使用的布局文件为setContentView()方法中所调用的文件,即activity_hello.xml。
- 当页面创建完成后,向AndroidManifest.xml的application中添加Activity声明,内容如下所示,
<activity android:name=".HelloActivity" />
4.在MainActivity.java中添加方法goHello(View view),当按钮被点击时,本方法将会被调用。代码如下所示
public void goHello(View view) {
Intent intent = new Intent(this, HelloActivity.class);
startActivity(intent);
}
5.重新Build你的项目,并在模拟器上运行,尝试点击按钮,如可成功跳转至新页面,那么恭喜你,完成了本章的内容。