第一行代码系列第二章——使用显式Intent在活动中穿梭

本文介绍如何在Android应用中从一个活动(Activity)启动另一个活动。通过创建新的布局文件和活动类,设置按钮点击事件来启动新活动。适用于初学者了解Android应用中活动间的跳转机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1效果图

按下button 1 之后 进入secondactivity活动


2建立一个新的活动

(1)建立一个新的布局文件second.xml,在res/layout文件中

建议如下代码活动(一个Button)

<?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" >
    
   <span style="color:#FF0000;"> <Button
        android:id="@+id/button_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 2"
        />
    </span>

</LinearLayout>
(2)在src中建立新的java,建立新的活动SecondActivity继承Activity

package com.example.activitytest;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class SecondActivity <span style="color:#FF0000;">extends Activity</span>{
	
	<span style="color:#FF0000;">@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.second);</span>
	}

}

(3)最后在菜单文件中为SecondActivity进行注册

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity 
        android:name=".FirstActivity"
        android:label="This is FirstActivity" 
        >
          <intent-filter >
              <action android:name="android.intent.action.MAIN"/>
              <category android:name="android.intent.category.LAUNCHER"/>
          </intent-filter>
        </activity>
        
        
      <span style="color:#FF0000;">  <activity android:name=".SecondActivity">
        </activity></span>
    </application>

(4)修改FirstActivity按钮的点击事件

Button button1 = (Button) findViewById(R.id.button_1);
		button1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//Toast .makeText(FirstActivity .this, "you click the button 1", Toast.LENGTH_SHORT).show();
			    <span style="color:#FF0000;">Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
			    startActivity(intent);</span>
			}
		});
	}

这样就可以用第一个活动来启动第二个活动!!!



~!~


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值