Android学习手记(1) Activity跳转
-
新建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的功能。
版权声明:本文为博主原创文章,未经博主允许不得转载。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步