【问题标题】:Why is the style of my programmatically created button different?为什么我以编程方式创建的按钮的样式不同?
【发布时间】:2021-07-05 17:38:59
【问题描述】:

在 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 布局相同的样式的正确方法是什么?

【问题讨论】:

    标签: android android-layout android-view android-button material-components-android


    【解决方案1】:

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

    要使用相同的按钮:

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

    【讨论】:

    • 谢谢!这对我行得通!不过,我确实有几个问题。有没有地方我可以阅读更多关于这种行为的信息?我也很好奇是否有一种机制可以自动选择正确的按钮/视图子类。也许像 theme.newButton(..) 这样会根据当前主题选择正确的 Button 类?
    • @math4tots 在基本主题中定义为&lt;item name="viewInflaterClass"&gt;com.google.android.material.theme.MaterialComponentsViewInflater&lt;/item&gt;。这个class 在运行时被调用并替换了一些小部件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多