-
新建Project,并将主页命名为MainActivity。
-
创建一个Activity
在App上“右键->New->Activity->Empty Activity”, 将新建的Activity命名为AnotherAty。 -
在MainActivity上添加一个按钮,并设置 id 和 text 属性
打开”activity_main.xml”, 添加如下代码:
1 <Button 2 android:layout_width="wrap_content" 3 android:layout_height="wrap_content" 4 android:text="Another Activity" 5 android:id="@+id/btnStartAnotherAty" 6 android:layout_below="@+id/textView" 7 android:layout_alignParentLeft="true" 8 android:layout_alignParentStart="true" />
4. 为按钮添加行为
打开“MainActivity.java”,在OnCreate方法内添加:
1 findViewById(R.id.btnStartAnotherAty).setOnClickListener(new View.OnClickListener() { 2 @Override 3 public void onClick(View v) { 4 startActivity(new Intent(MainActivity.this,AnotherAty.class)); 5 } 6 });
这是完整代码:
1 public class MainActivity extends AppCompatActivity { 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_main); 7 8 findViewById(R.id.btnStartAnotherAty).setOnClickListener(new View.OnClickListener() { 9 @Override 10 public void onClick(View v) { 11 startActivity(new Intent(MainActivity.this,AnotherAty.class)); 12 } 13 }); 14 } 15 }
这样就实现了单击MainActivity中的Button跳转到AnotherAty的功能。
版权声明:本文为博主原创文章,未经博主允许不得转载。