问题描述
从 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)