首页 > 解决方案 > Android 视图绑定。如何在 Basic Activity/Fragment 中实现绑定?

问题描述

我正在处理视图绑定。请指导我是否可以在基本活动中派生绑定逻辑以及如何创建它?谢谢。我正在尝试这样做,但这段代码无法编译。

public class BasicActivity<Т extends ViewBinding> extends AppCompatActivity {

    private Т binding;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        binding = T.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }
}

标签: javaandroidkotlin

解决方案


你只能用我认为的抽象方法来做到这一点。我使用类似下面的东西。

abstract class BaseActivity<V : ViewBinding> : AppCompatActivity() {
    protected open var binding: V? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        makeFullScreen()
        setContentView(getInflatedLayout(layoutInflater))
        setup()
        SharePreferenceUtil.setListenerFlutter(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        this.binding = null
        SharePreferenceUtil.removeListenerFlutter(this)
    }


    //internal functions
    private fun getInflatedLayout(inflater: LayoutInflater): View {
        this.binding = setBinding(inflater)


        return binding?.root
                ?: error("Please add your inflated binding class instance")
    }

    //abstract functions
    abstract fun setBinding(layoutInflater: LayoutInflater): V

    abstract fun setup()
}

如果你想要片段摘要,你可以像下面这样

abstract class BaseFragment<T : ViewBinding, A : Any> : Fragment() {
    protected var handler: A? = null //It's base activity

    protected open var binding: T? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        @Suppress("UNCHECKED_CAST")
        this.handler = this.activity as? A
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        this.binding = this.setBinding(inflater,container)
        return binding!!.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
    }
    abstract fun setBinding(inflater: LayoutInflater, container: ViewGroup?): T
}

然后在片段中设置绑定;

override fun setBinding(inflater: LayoutInflater, container: ViewGroup?): ActivityMainBinding = ActivityMainBinding.inflate(inflater, container, false)

推荐阅读