gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:50:11 25 4
gpt4 key购买 nike

从 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
第一个和第二个按钮似乎有不同的风格。
他们为什么不同?此外,以编程方式创建新 View 的正确方法是什么,以便以编程方式创建的 View 具有与其对应的 xml 布局相同的样式?

最佳答案

它们是不同的,因为您使用的是 Theme.MaterialComponents.*主题。
有了这个主题 Button布局中定义的是 replaced at runtime来自 MaterialButton .
要使用相同的按钮,您必须使用:

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

关于android - 为什么我以编程方式创建的按钮的样式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67027908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com