微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我以编程方式创建的按钮的样式不同?

如何解决为什么我以编程方式创建的按钮的样式不同?

从 Android Studio一个空 Activity 的新项目开始,我在 activity_main.xml添加一个带有单个按钮的线性布局:

<LinearLayout
    android:id="@+id/buttons"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Demo01" />
</LinearLayout>

然后在我的 MainActivity 中,我以编程方式添加第二个按钮:

val buttonsLayout = findViewById<LinearLayout>(R.id.buttons)
val button = Button(this)
button.layoutParams = ViewGroup.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT,ActionBar.LayoutParams.WRAP_CONTENT
)
button.text = "Demo 01"
buttonsLayout.addView(button)

最后当我运行这个应用程序时,我看到了:

buttons with different colors

一个和第二个按钮似乎有不同的样式。

为什么不同?此外,以编程方式创建新视图以便以编程方式创建的视图具有与其对应的 xml 布局相同的样式的正确方法是什么?

解决方法

它们不同,因为您使用的是 Theme.MaterialComponents.* 主题。
对于此主题,布局中定义的 ButtonMaterialButtonreplaced at runtime

要使用您必须使用的相同按钮:

    val buttonsLayout = findViewById<LinearLayout>(R.id.buttons)
    val button = MaterialButton(this)
    //...
    button.text = "Demo01"
    buttonsLayout.addView(button)

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。