java - 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());
}
}
解决方案
你只能用我认为的抽象方法来做到这一点。我使用类似下面的东西。
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)
推荐阅读
- windows-10 - Windows 10 S 模式下的驱动程序返回“证书已被其颁发者明确吊销”。
- javascript - 在模式关闭时重置/清除获取的数据
- powershell - Powershell 允许取消启动进程 -wait
- excel - 我想在 xpath 中设置一个值到 x /// tr[x]
- javascript - 用带有 css 和 javascript 的页面加载器覆盖整个身体?
- database - 有没有办法将 .db 文件转换为 .accdb 文件
- python - 我无法得到元素的所有结果
- sql - 如何以递归方式在 Hiveql 中生成数字序列?
- python - 如何用逗号替换多种类型的分隔符
- javascript - Javascript控制台输出不同的值然后在文本上