为什么以编程方式创建的按钮的样式不同? [英] Why is the style of my programmatically created button different?
问题描述
从Android Studio中的活动为空的新项目开始,我在 activity_main.xml
中使用单个按钮添加线性布局:
< LinearLayoutandroid:id =" @ + id/buttons"android:layout_width =" match_parent"android:layout_height =" wrap_content"android:gravity ="center"android:orientation =" vertical"><按钮android:layout_width =" wrap_content"android:layout_height =" wrap_content"android:text =" Demo01" ;;/></LinearLayout>
然后在我的 MainActivity
中,以编程方式添加第二个按钮:
val buttonLayout = findViewById< LinearLayout>(R.id.buttons)val button =按钮(此)button.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ActionBar.LayoutParams.WRAP_CONTENT)button.text =演示01";ButtonsLayout.addView(button)
最后,当我运行此应用程序时,我看到了:
第一个和第二个按钮似乎具有不同的样式.
为什么它们不同?此外,以编程方式创建新视图的正确方法是什么,以使以编程方式创建的视图具有与xml布局副本相同的样式?
它们是不同的,因为您使用的是 Theme.MaterialComponents.*
主题.
有了这个主题,布局中定义的 Button
是
Starting with a new project in Android Studio with an empty Activity, I add a linear layout with a single button in 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>
then in my MainActivity
, I programmatically add a second button:
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)
Finally when I run this app, I see this:
The first and second buttons seem to have different styles.
Why are they different? Furthermore, what's the correct way to programmatically create new views so that the programmatically created views have the same style as their xml layout counterparts?
They are different because you are using a Theme.MaterialComponents.*
theme.
With this theme the Button
defined in the layout is replaced at runtime by a MaterialButton
.
To have the same button you have to use:
val buttonsLayout = findViewById<LinearLayout>(R.id.buttons)
val button = MaterialButton(this)
//...
button.text = "Demo01"
buttonsLayout.addView(button)
这篇关于为什么以编程方式创建的按钮的样式不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!