Kotlin 实现Activity之间的跳转 和 布局控件的简单调用

开始自学kotlin的时候,为了方便简单的在这做下记录,简单使用Activity之间的跳转

  • 在MainActivity中布局正常添加一个button按钮如下代码:
 <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="跳转按钮"
            android:onClick="startActivity"/>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5
  • 在MainActivity代码中使用kotlin语言进行跳转:
 fun jump(view: View) {
        val intent = Intent() 
        //获取intent对象
        intent.setClass(this,Main2Activity::class.java)
         // 获取class是使用::反射
        startActivity(intent)
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

kotlin的控件对象的获取 调用:

  • 如下简单布局显示:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.eq.tanchudemo.Main2Activity">

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="要改变的控件"/>
</RelativeLayout>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 在kotlin代码中如下操作即可:
class Main2Activity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        textview.text = "sdfadsfds" //直接使用布局中定义的id,不需要获取
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

另外还有一种写法是findviewbyid类型的


class MainActivity : AppCompatActivity() {

    private var b1: Button? = null  //先声明
    private var b2: Button? = null
    private var b3: Button? = null
    private var isOpen = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        b1 = findViewById(R.id.one) as Button //在获取
        b2 = findViewById(R.id.two) as Button
        b3 = findViewById(R.id.three) as Button
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值