1. Introduction
This article is a simple encapsulation used by databinding, mainly in the base classes BaseActivity and BaseFragment
2. Specific steps
1. Enable databinding in build.gradle
dataBinding {
enabled = true }
2. In the encapsulation of BaseActivity, it is mainly acquired through reflection. as follows
package com.zw.databindingdemo.java;
import android.os.Bundle;
import android.view.LayoutInflater;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.ViewDataBinding;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
/**
* 描述:
* @author: dd
* @time: 2023/6/8 16:33
*/
public abstract class BaseActivity<VB extends ViewDataBinding> extends AppCompatActivity {
public VB mBinding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createBinding();
}
private void createBinding() {
Class<VB> vbClass = getVbClass();
try {
if (vbClass == null) {
return;
}
Method method = vbClass.getMethod("inflate", LayoutInflater.class);
mBinding = (VB) method.invoke(null, getLayoutInflater());
setContentView(mBinding.getRoot());
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
}
private Class<VB> getVbClass() {
ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();
if (parameterizedType == null) {
return null;
}
Class<VB> vbClass = (Class<VB>) parameterizedType.getActualTypeArguments()[0];
return vbClass;
}
}
3. Use the following in Activity
package com.zw.databindingdemo.java;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.zw.databindingdemo.databinding.ActivityTestBinding;
/**
* 描述:
* @author: dd
* @time: 2023/6/8 16:33
*/
public class TestActivity extends BaseActivity<ActivityTestBinding> {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding.tvName.setText("测试 java Activity");
mBinding.btnGo.setOnClickListener(v -> {
initFragment();
});
}
private void initFragment() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(mBinding.frameLayout.getId(), new TestFragment());
ft.commit();
}
}
4. Encapsulation in BaseFragment
package com.zw.databindingdemo.java;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
/**
* 描述:
* @author: dd
* @time: 2023/6/8 16:33
*/
public abstract class BaseFragment<VB extends ViewDataBinding> extends Fragment {
public VB mBinding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
createBinding(inflater, container);
return mBinding.getRoot();
}
private void createBinding(LayoutInflater inflater, ViewGroup container) {
Class<VB> vbClass = getVbClass();
try {
if (vbClass == null) {
return;
}
/* Method method = vbClass.getMethod("inflate", LayoutInflater.class, ViewGroup.class, Boolean.class);*/
Method method = vbClass.getMethod("inflate", LayoutInflater.class);
mBinding = (VB) method.invoke(null, inflater);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
}
private Class<VB> getVbClass() {
ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();
if (parameterizedType == null) {
return null;
}
return (Class<VB>) parameterizedType.getActualTypeArguments()[0];
}
}
5. The use in Fragment is as follows
package com.zw.databindingdemo.java;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.zw.databindingdemo.databinding.FragmentTestBinding;
/**
* 描述:
* @author: dd
* @time: 2023/6/8 16:33
*/
public class TestFragment extends BaseFragment<FragmentTestBinding> {
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBinding.tvName.setText("测试 java Fragment");
}
}
6. Kotlin version
package com.zw.databindingdemo.kotlin
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import java.lang.reflect.ParameterizedType
/**
* 描述:
* @author: dd
* @time: 2023/6/8 16:33
*/
abstract class BaseActivityKotlin<VB : ViewDataBinding> : AppCompatActivity() {
public lateinit var mBinding: VB
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = createBinding()
setContentView(mBinding.root)
}
private fun createBinding(): VB {
val vbClass = getVBClass()
val method = vbClass.getMethod("inflate", LayoutInflater::class.java)
return method.invoke(null, layoutInflater) as VB
}
@Suppress("UNCHECKED_CAST")
private fun getVBClass(): Class<VB> {
val type = javaClass.genericSuperclass as ParameterizedType
return type.actualTypeArguments[0] as Class<VB>
}
}
package com.zw.databindingdemo.kotlin
import android.os.Bundle
import com.zw.databindingdemo.databinding.ActivityTestKotlinBinding
/**
* 描述:
* @author: dd
* @time: 2023/6/8 16:33
*/
class TestActivityKotlin: BaseActivityKotlin<ActivityTestKotlinBinding>() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding.tvName.text = "测试 Kotlin Activity"
mBinding.btnGo.setOnClickListener {
initFragment() }
}
private fun initFragment() {
val fm = supportFragmentManager
val ft = fm.beginTransaction()
ft.replace(mBinding.frameLayout.id, TestFragmentKotlin())
ft.commit()
}
}
package com.zw.databindingdemo.kotlin
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import java.lang.reflect.ParameterizedType
/**
* 描述:
* @author: dd
* @time: 2023/6/8 16:33
*/
abstract class BaseFragmentKotlin<VB : ViewDataBinding> : Fragment() {
public lateinit var mBinding: VB
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mBinding = createBinding(inflater, container)
return mBinding.root
}
private fun createBinding(inflater: LayoutInflater, container: ViewGroup?): VB {
val vbClass = getVBClass()
val method = vbClass.getMethod(
"inflate",
LayoutInflater::class.java,
ViewGroup::class.java,
Boolean::class.java
)
return method.invoke(null, inflater, container, false) as VB
}
@Suppress("UNCHECKED_CAST")
private fun getVBClass(): Class<VB> {
val type = javaClass.genericSuperclass as ParameterizedType
return type.actualTypeArguments[0] as Class<VB>
}
}
package com.zw.databindingdemo.kotlin
import android.os.Bundle
import android.view.View
import com.zw.databindingdemo.databinding.FragmentTestKotlinBinding
/**
* 描述:
* @author: dd
* @time: 2023/6/8 16:33
*/
class TestFragmentKotlin : BaseFragmentKotlin<FragmentTestKotlinBinding>() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mBinding.tvName.text = "测试 Kotlin Fragment"
}
}
at last
If you want to become an architect or want to break through the 20-30K salary range, then don't be limited to coding and business, but you must be able to select models, expand, and improve programming thinking. In addition, a good career plan is also very important, and the habit of learning is very important, but the most important thing is to be able to persevere. Any plan that cannot be implemented consistently is empty talk.
If you have no direction, here I would like to share with you a set of "Advanced Notes on the Eight Major Modules of Android" written by the senior architect of Ali, to help you organize the messy, scattered and fragmented knowledge systematically, so that you can systematically and efficiently Master the various knowledge points of Android development.
Compared with the fragmented content we usually read, the knowledge points of this note are more systematic, easier to understand and remember, and are arranged strictly according to the knowledge system.
Full set of video materials:
1. Interview collection
2. Source code analysis collection
3. The collection of open source frameworks
welcomes everyone to support with one click and three links. If you need the information in the article, directly scan the CSDN official certification WeChat card at the end of the article to get it for free↓↓↓
PS: There is also a ChatGPT robot in the group, which can answer your work or technical questions