我有一个从Fragment扩展而来的BaseFragment
目前我的BaseFragment是这个
open class BaseFragment : Fragment() {
private lateinit var onInteractionListener: OnFragmentInteractionListener
val toolbar : Toolbar?
get() {
return if(activity is BaseActivity)
(activity as BaseActivity).toolbar
else
null
}
override fun onAttach(context: Context) {
super.onAttach(context)
setOnInteractionListener(context)
}
...
问题是,当我扩展这个 fragment 时,我需要像往常一样使用 onCreateView,但我想要完成的是在扩展时使用 BaseFragment(LayoutResource) 内的 fragment 布局作为可选,就像 fragment 重载方法一样
/**
* Alternate constructor that can be used to provide a default layout
* that will be inflated by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
*
* @see #Fragment()
* @see #onCreateView(LayoutInflater, ViewGroup, Bundle)
*/
@ContentView
public Fragment(@LayoutRes int contentLayoutId) {
this();
mContentLayoutId = contentLayoutId;
}
如何在 BaseFragment 中实现此功能?所以当我扩展它时我可以做到
class A: BaseFragment(R.layout.myFragment)
或
class A: BaseFragment()
onCreateView(...) { ... }
谢谢!
最佳答案
只需让主构造函数将参数传递给 super 构造函数即可。提供默认值零,您也可以将其用作无参数构造函数:
open class BaseFragment(@LayoutRes contentLayoutId : Int = 0) : Fragment(contentLayoutId) {
/// your class body
}
关于android - 如何在 BaseFragment() 中传递 fragment 布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64649117/