如何解决为什么我以编程方式创建的按钮的样式不同?
从 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)
最后当我运行这个应用程序时,我看到了:
第一个和第二个按钮似乎有不同的样式。
为什么不同?此外,以编程方式创建新视图以便以编程方式创建的视图具有与其对应的 xml 布局相同的样式的正确方法是什么?
解决方法
它们不同,因为您使用的是 Theme.MaterialComponents.*
主题。
对于此主题,布局中定义的 Button
是 MaterialButton
的 replaced at runtime。
要使用您必须使用的相同按钮:
val buttonsLayout = findViewById<LinearLayout>(R.id.buttons)
val button = MaterialButton(this)
//...
button.text = "Demo01"
buttonsLayout.addView(button)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。