Android Studio 点击按钮跳转到另一个Activity

这篇博客记录了Android Studio初学者如何创建新界面、添加按钮并实现点击按钮通过Intent进行页面跳转。首先,创建Empty Activity并在XML布局文件中配置按钮。接着,在MainActivity中实例化并绑定按钮,为每个按钮设置监听器。最后,介绍了显式Intent和隐式Intent的区别,展示了如何使用Intent启动不同类型的Activity。

一、前言

最近才开始使用Android Studio,不太熟悉,用博客记录一下。

二、前置工作

2.1创建新的界面和按钮

创建一个新的empty activity,并且在新创建的activity的配置文件里配置按钮,也就是xml文件。
配置按钮的代码:

<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="方式一"
        android:id="@+id/type1"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="方式二"
        android:id="@+id/type2"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="方式三"
        android:id="@+id/type3"/>

2.2、绑定按钮

在mainactivity里创建几个按钮对象,并且将按钮对象与按钮示例绑定,
代码:

Button btn_type1;
    Button btn_type2;
    Button btn_type3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_type1=(Button) findViewById(R.id.type1);
        btn_type2=(Button) findViewById(R.id.type2);
        btn_type3=(Button) findViewById(R.id.type3);
        btn_type1.setOnClickListener(this);
        btn_type2.setOnClickListener(this);
        btn_type3.setOnClickListener(this);
    }

三、intent进行连接并跳转

显示Intent和隐式Intent的用法不一样,隐式的话步骤要多一步,要在AndroidManifest.xml里要用的activity里加入以下代码,action那里可以随便改,只要后面引用的时候与之对应就行,category那里是一个默认参数

 <activity
            android:name=".dateActivity"
            android:exported="true" >
            <intent-filter>
                <action android:name="zxs.study.dateActivity"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>```
引用(用的时候记得加一个接口 :implements View.OnClickListener):

```java
public void onClick(View view) {
        Intent intent=new Intent();
        switch (view.getId()){
            case R.id.type1:
                intent.setClass(this,clockActivity.class);
                break;
            case R.id.type2:
                intent.setAction("zxs.study.dateActivity");
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                break;
            case R.id.type3:
                intent.setClassName("com.example.myapplication","com.example.myapplication.MainActivity");
                break;


        }
        startActivity(intent);
    }

startActivity(intent)不能丢。

四、总结

setp1:创建新窗口
step2:创建按钮并绑定
step3:用intent完成连接,如果是隐式需要多配置一步。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值