相信大家在剛開始觸碰 Android 的時候一定會有一個疑惑,看到市面上那麼多 App 頁面都會跳來跳去,可是我試半天,怎麼我的 App 像隻死老鼠一動也不動呢?
唉呀!其實這有一個小小的訣竅哦!今天由小編來教大家,如何運用簡單的兩行程式碼,來讓大家輕鬆跳頁!
首先,我們先在 layout 裡面準備兩個待會會用到的 xml 文件,第一個裡頭要放置一個 Button 作為等等跳頁的觸發物件,兩個 xml 皆放一個 TextView 與更改背景顏色,作為證明真的有跳頁!
路徑:res/layout/activity_intent.xml<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ddeeff"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textStyle="bold"
android:text="this is A page of Mr.Ray's Box" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to page B" />
</LinearLayout>
路徑:res/layout/page_b.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffeedd"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="this is B page of Mr.Ray's Box"
android:textSize="20dp"
android:textStyle="bold" />
</LinearLayout>
接下來就要來寫程式囉!在這裡一樣要弄出兩個 Activity,一個負責顯示 Page A 並弄一個可以跳到 Page B 的按鈕,一個負責顯示 Page B 就夠了。
File Name:IntentActivitypublic class IntentActivity extends Activity {
private Button btn_go;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent);
btn_go = (Button) findViewById(R.id.btn);
btn_go.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 設定從這個活動跳至 PageB 的活動
Intent intent = new Intent(IntentActivity.this, PageB.class);
// 開始跳頁
startActivity(intent);
}
});
}
}
File Name:PageB
public class PageB extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page_b);
}
}
如此一來,就可以輕鬆跳頁囉!我們來看看最後的成果吧!
| 一開始進去的畫面,點選按鈕就會跳至 Page B。 |
| Yes!看來跳得很成功哦! |
那我B要跳回A呢?
回覆刪除那我按返回建呢?
B跳回A可以按返回鍵
刪除按返回鍵會跳回A
如果你想一次關多個頁面
可以用finish指令搭配判斷式