1.在需要的模块或项目中添加
android { dataBinding { enabled = true } }
2.创建数据模型
package com.example.library.bean; public class Skip { public String skipContent; public Skip(String skipContent) { this.skipContent = skipContent; } public String getSkipContent() { return skipContent; } public void setSkipContent(String skipContent) { this.skipContent = skipContent; } }
3.在布局中使用
<?xml version="1.0" encoding="utf-8"?> <layout 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" tools:context=".activty.SplashActivty"> <!--tools:context=".activty.SplashActivty" 当前的Layout所在的渲染上下文是activity name对应的那个activity>--> <data> <variable name="Skip" type="com.example.library.bean.Skip" /> <variable name="clickListener" type="android.view.View.OnClickListener" /> </data> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bg_splash"> <Button android:id="@+id/splash_skip_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:layout_marginTop="2dp" android:layout_marginRight="2dp" android:text="@{Skip.skipContent}" android:background="#CDDC39" android:textColor="#000000" android:onClick="@{clickListener}"/> </FrameLayout> </layout>
4.在项目中使用
package com.example.library.activty; import android.view.View; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import com.example.library.R; import com.example.library.activty.base.BaseActivty; import com.example.library.bean.Skip; import com.example.library.databinding.ActivitySplashActivtyBinding; public class SplashActivty extends BaseActivty implements View.OnClickListener { private ActivitySplashActivtyBinding viewDataBinding; @Override public void initLayout() { viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_splash_activty ); } @Override public void initView() { } @Override public void initData( ) { Skip skip=new Skip("跳过"); viewDataBinding.setSkip(skip); viewDataBinding.setClickListener(this); } @Override public void onClick(View v) { if (v.getId() == R.id.splash_skip_btn) { openActivty(HomeActivity.class); } } }