android studio 中使用kotlin语言 直接操作布局id

android studio 中使用kotlin语言 直接操作布局id
需要在 build.gradle 文件 引入

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

(会自动生成,可忽略)然后在 Activity 文件中 引入 对应的 layout 文件 如:activity_main.xml

import kotlinx.android.synthetic.main.activity_main.*

然而,运行是会提示kotlin-android-extensions废弃

Android StudioThe ‘kotlin-android-extensions‘ Gradle plugin is deprecated.

所以我们采用viewbinding来直接操作布局id

一、ViewBinding开启
在app下build.grade中加入以下代码

AS 3.6.x

android {
	...
     viewBinding{
        enabled = true
  	}
}

AS 4.0.x

android {
	...
    buildFeatures{
        viewBinding= true
    }
}

开启之后,创建xml布局文件时,编译器会自动化生成对应的xxxBinding文件。例如:activity_main.xml 对应生成ActivityMainBinding,下面进行代码演示

一、Activity中使用ViewBinding
1、创建MainActivity、activity_main.xml文件


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/iv_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/transparent" />


    <FrameLayout
        android:id="@+id/fl_contain"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

2、Java中把自动生成的ActivityMainBinding进行填充绑定后再 setContentView(rootView);

        //关键代码:binding xml布局
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        View rootView = mBinding.getRoot();
        setContentView(rootView);

3、绑定之后就可以直接通过mBinding.xxx(xxx==id)使用控件,完整代码如下:

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding mBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //关键代码:binding xml布局
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        View rootView = mBinding.getRoot();
        setContentView(rootView);

        //使用介绍
        mBinding.ivTest.setBackground(ContextCompat.getDrawable(this, R.mipmap.ic_launcher));

        mBinding.flContain.setOnClickListener(v -> {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.add(R.id.fl_contain, new BindViewFragment());
            transaction.commit();
        });
    }
}

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值