Android學習筆記——Activity之間的跳轉(五)
阿新 • • 發佈:2018-12-09
1:使用Intent(意圖)的方式實現Activity跳轉
(1)MainActivity.java: public class MainActivity extends Activity { private Button startOther; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startOther=(Button) findViewById(R.id.button); startOther.setOnClickListener(new StartListener()); } class StartListener implements OnClickListener{ @Override public void onClick(View v) { // 當點選事件觸發後執行,啟動OtherActivity //建立一個Intent物件 Intent intent=new Intent(); //呼叫setClass方法指定啟動某一個Activity intent.setClass(MainActivity.this, OtherActivity.class); //呼叫startActivity startActivity(intent); } } } (2)OtherActivity.java //建立一個類繼承自Activity public class OtherActivity extends Activity { @Override //重寫onCreate方法,當前Activity的入口 protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_other); } } (3)activity_main.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" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="第一個Activity" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="啟動OtherActivity"/> </LinearLayout> (4)activity_other.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:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="這是第二個Activity"/> </LinearLayout>
2:BackStack回退棧(先進後出)