【问题标题】:Custom Button is not inflating correctly自定义按钮未正确充气
【发布时间】:2022-01-14 19:04:39
【问题描述】:

这可能是一个非常简单的问题.. 但我就是想不通这个问题。

我只是像这样扩展了 MaterialButton

class MyButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : MaterialButton(context, attrs, defStyleAttr)

然后把它放在 XML 中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/b1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name" />

    <com.example.myapplication.MyButton
        android:id="@+id/b2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name" />
</LinearLayout>

输出是

它变成了一个TextView。我已经在 gradle 中添加了材料库

implementation 'com.google.android.material:material:1.4.0'

任何帮助!谢谢

【问题讨论】:

  • defStyleAttr = R.attr.materialButtonStyle - 你的构造函数参数的默认值有误。
  • 就像魔术一样工作。谢谢@MikeM。

标签: android android-layout android-custom-view


【解决方案1】:

用这个改变你的 MyButton 标签

<com.example.myapplication.MyButton
        android:id="@+id/b2"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name" />

【讨论】:

    猜你喜欢
    • 2020-05-29
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    相关资源
    最近更新 更多