【问题标题】:Android Button View Binding ClickListener not workingAndroid按钮视图绑定ClickListener不起作用
【发布时间】:2021-11-20 22:43:20
【问题描述】:

我的按钮上的 clickListener 不起作用,我想知道是否存在已知问题或我遗漏了什么?:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    mMainBinding = MainBinding.inflate(layoutInflater)
    setContentView(R.layout.main)
}

override fun onStart() {
    super.onStart()
    val button = findViewById<Button>(R.id.login_button)
    mMainBinding.loginButton.setOnClickListener {
        ...
    }
}

我尝试将 mMainBinding 初始化移到 setContentView 下面,尝试使用 MaterialButton 和普通按钮。使用用 findViewById 初始化的“按钮”它可以工作,但使用它不能使用绑定。如果我 ctrl + 单击 loginButton 它会导航到 xml 布局中的右侧按钮,该按钮也是可点击的,那么我错过了什么?

【问题讨论】:

  • setContentView(R.layout.main) - 这是创建一个完全独立于绑定设置的布局实例。您需要改为使用mMainBinding.root 调用setContentView()
  • @MikeM。就是这样!谢谢!我之前有mMainBinding.root,但是Android Studio在通过bindnig设置时没有在类声明旁边列出布局文件,所以我改变了它。奇怪的是,并不是我用 binding.root 设置了布局,而是我遇到了一个新问题,布局的边距被忽略了,所以我认为这是一个新问题。
  • 没问题。您是指根视图上的边距吗?改用DataBindingUtils.setContentView() methods 之一可能会解决这个问题。至少,从源代码的快速浏览来看,它们似乎正确地使用其父级扩展布局。
  • 是的,根视图的边距被忽略。我没有使用 DataBinding,现在只使用 ViewBinding。
  • 哦,对了,您确实指定了View 绑定。我的错。

标签: android android-button android-viewbinding


【解决方案1】:

如果你使用的是Activity那么你可以尝试使用->

binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

如果您使用的是 Fragment,请尝试 - >

binding = DataBindingUtil.inflate(inflater, R.layout.fragment_your_videos, container, false); 视图 = binding.getRoot(); 返回视图;

可能是DataBinding的问题

【讨论】:

    猜你喜欢
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多