自定义视图上的数据绑定导致类型不匹配

问题描述

我有一个自定义视图 (LoadingButton),当通过数据绑定将其链接到片段中的变量时,会导致以下错误Type mismatch: inferred type is View but LoadingButton was expected

但是当我使用 findViewById 时,它工作得很好。在这种情况下如何使用数据绑定?

显然,这个问题需要更多的文字,因为stackoverflow中有一条错误消息,上面写着“看起来你的帖子主要是代码;请添加更多细节”,所以我想必须写更多细节:

代码

[FRAGMENT] 登录Fragment.kt

class LoginFragment : Fragment() {

    private lateinit var binding: FragmentLoginBinding
    private lateinit var login: LoadingButton

    override fun onCreateView(
        inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?
    ): View {
        binding = FragmentLoginBinding.inflate(inflater,container,false)
        binding.mainviewmodel = mainviewmodel
        return binding.root
    }

    override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
        super.onViewCreated(view,savedInstanceState)
        initUi()
    }

    private fun initUi() {
        login = binding.buttonLoginLogin    // causes error
        // login = requireActivity().findViewById(R.id.button_login_login) // doesn't cause error
    }

[布局 XML] fragment_login.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.myapp.LoadingButton
            android:id="@+id/button_login_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

[自定义视图 XML] view_loading_button.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:clipChildren="false">

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="4dp"
        app:layout_constraintTop_toTopOf="@id/button"
        app:layout_constraintStart_toStartOf="@id/button"
        app:layout_constraintBottom_toBottomOf="@id/button"
        app:layout_constraintEnd_toEndOf="@id/button"
        android:elevation="4dp"/>

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:layout_margin="4dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

[自定义视图类] LoadingButton.kt

class LoadingButton @JvmOverloads constructor(
    context: Context,attrs: AttributeSet? = null,defStyleAttr: Int = 0
) :
    ConstraintLayout(context,attrs,defStyleAttr) {

    private val button: Button
    private val progressBar: ProgressBar
    private var loading: Boolean = false
    private var buttonText: String = ""

    private var textColor: Int


    init {
        inflate(context,R.layout.view_loading_button,this)
        button = findViewById(R.id.button)
        progressBar = findViewById(R.id.progressBar)

        context.theme.obtainStyledAttributes(attrs,R.styleable.LoadingButton,0).apply {
            try {
                loading = getBoolean(R.styleable.LoadingButton_loading,false)
                buttonText = getString(R.styleable.LoadingButton_text).toString()
                textColor = getInt(R.styleable.LoadingButton_textColor,0)
                button.setTextColor(textColor)
                button.text = buttonText
                button.background = getDrawable(R.styleable.LoadingButton_buttonBackground)
                setLoading(loading)
            } finally {
                recycle()
            }
        }
    }


    fun setLoading(isLoading: Boolean) {
        loading = isLoading
        if (loading) {
            this.isClickable = false
            button.isClickable = false
            buttonText = button.text.toString()
            button.text = ""
            progressBar.visibility = View.VISIBLE
        } else {
            this.isClickable = true
            button.isClickable = true
            button.text = buttonText
            progressBar.visibility = View.GONE
        }
        invalidate()
        requestLayout()
    }
}

解决方法

当代码在其他用户的 IDE 上编译时,这似乎是某种错误。 对我有用的解决方法是明确地强制转换(尽管 IDE 提出抗议):

    it('should return a product',async () => {
      const result: Product = {
        name: 'product',price: 100,category: 'junk',};

      // this line
      (service as any).products = new Map([
         ["id",product],]);

      expect(await service.findOne('id')).toStrictEqual(result);
    });