首页 > 代码库 > 二个Activity之间的切换

二个Activity之间的切换

1.在项目中新建一个activity_second.xml和SecondActivity.java.

2.二个布局文件中都定义了一个TextView和Button。

activity_main.xml

 1 <?xml version="1.0" encoding="utf-8"?> 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 3     xmlns:tools="http://schemas.android.com/tools" 4     android:layout_width="match_parent" 5     android:layout_height="match_parent" 6     android:paddingBottom="@dimen/activity_vertical_margin" 7     android:paddingLeft="@dimen/activity_horizontal_margin" 8     android:paddingRight="@dimen/activity_horizontal_margin" 9     android:paddingTop="@dimen/activity_vertical_margin"10     tools:context="com.hsiehway.mysample01.MainActivity">11 12     <TextView13         android:layout_width="wrap_content"14         android:layout_height="wrap_content"15         android:text="第一个Activity"16         android:id="@+id/textView" />17 18     <Button19         android:layout_width="wrap_content"20         android:layout_height="wrap_content"21         android:text="切换到第二个Activity"22         android:id="@+id/myBtn01"23         android:layout_below="@+id/textView"24         android:layout_alignParentLeft="true"25         android:layout_alignParentStart="true" />26 </RelativeLayout>

3.SecondActivity.java

 1 package com.hsiehway.mysample01; 2  3 import android.os.Bundle; 4 import android.support.annotation.Nullable; 5 import android.support.v7.app.AppCompatActivity; 6  7 public class SecondActivity extends AppCompatActivity { 8     @Override 9     protected void onCreate(@Nullable Bundle savedInstanceState) {10         super.onCreate(savedInstanceState);11         setContentView(R.layout.activity_second);12     }13 }

4.在AndroidManifest.xml中声名SecondActivity

1 <activity android:name=".SecondActivity"></activity>

5.MainActivity.java

 1 package com.hsiehway.mysample01; 2  3 import android.content.Intent; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.widget.Button; 8  9 public class MainActivity extends AppCompatActivity {10 11     private Button mybutton;12 13     @Override14     protected void onCreate(Bundle savedInstanceState) {15         super.onCreate(savedInstanceState);16         setContentView(R.layout.activity_main);17         mybutton = (Button)findViewById(R.id.myBtn01);18         //设置mybutton的按键监听器19         mybutton.setOnClickListener(new BtnListener());20     }21 22     class BtnListener implements View.OnClickListener{23         @Override24         public void onClick(View view) {25             //新建一个Intent对象26             Intent intent =new Intent();27             //指定intent要启动的类28             intent.setClass(MainActivity.this,SecondActivity.class);29             startActivity(intent);30             //关闭当前Activity31             finish();32         }33     }34 }

6.点击运行,就可以看到效果了.

二个Activity之间的切换