Android视图绑定。如何在基本活动/片段中实现绑定?

时间:2019-11-06 13:34:47

标签: 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());
    }
}

2 个答案:

答案 0 :(得分:5)

您只能使用我认为的抽象方法来执行此操作。我使用类似下面的内容。

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)

答案 1 :(得分:0)

您可以在“基本”活动中具有绑定逻辑

您可以使用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();