Hay*_*uka 6 java android kotlin
我正在研究视图绑定。请指导我是否可以在基本活动中导出绑定逻辑以及如何创建它?谢谢。我正在尝试这样做,但此代码无法编译。
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());
}
}
Run Code Online (Sandbox Code Playgroud)
你只能用我认为的抽象方法来做到这一点。我使用类似下面的东西。
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()
}
Run Code Online (Sandbox Code Playgroud)
如果你想要片段摘要,你可以像下面这样
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
}
Run Code Online (Sandbox Code Playgroud)
然后在片段中设置绑定;
override fun setBinding(inflater: LayoutInflater, container: ViewGroup?): ActivityMainBinding = ActivityMainBinding.inflate(inflater, container, false)
Run Code Online (Sandbox Code Playgroud)
您可以在基本活动中使用绑定逻辑
您可以使用 DataBindingUtil.setContentView() 并有一个抽象函数来获取布局 id。
protected T binding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, getLayoutId())
}
public abstract int getLayoutId();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2300 次 |
| 最近记录: |