【问题标题】:How to create Material Button Dynamically?如何动态创建材质按钮?
【发布时间】:2019-06-19 13:22:16
【问题描述】:

我正在尝试动态创建材质按钮。我已经添加了所有依赖项和所有内容。如果我在 XML 文件中创建它,它可以完美运行,但是当我尝试动态创建它时,它会给出错误

创建我尝试过的材质按钮:

MaterialButton materialButton = new MaterialButton(context);
    LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, 
    LayoutParams.WRAP_CONTENT);
    myLayout.addView(materialButton, layoutParams);```

我的样式 xml 如下所示:

<style name="AppTheme" 
parent="Theme.MaterialComponents.Light.NoActionBar">

它给出了运行时错误 “java.lang.IllegalArgumentException:此组件上的样式要求您的应用主题为 Theme.MaterialComponents(或后代)。”

找到答案: 将 getActivity() 作为上下文传递解决了我的问题

【问题讨论】:

  • 它会告诉你到底是什么问题。您需要在 Activity 上放置一个 Theme.MaterialComponents 或该主题的子主题的主题。
  • 错误说“应用程序主题是 Theme.MaterialComponents(或后代)”,我在样式中有
  • @AshimGhimire 看到我编辑的答案..它在我的应用程序中工作..这将是有帮助的

标签: android material-design


【解决方案1】:

只需在 Material Button 的构造函数中传递样式..

    MaterialButton materialButton = new MaterialButton(this, null, R.attr.borderlessButtonStyle);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
    linearHome.addView(materialButton, layoutParams);
    String buttonText = "Button Name";
    materialButton.setText(buttonText);
    materialButton.setTextColor(Color.RED);

【讨论】:

  • 已经改了。但我看不出有什么区别。但是感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2023-03-28
  • 2020-02-20
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
  • 2020-05-03
  • 2021-07-12
相关资源
最近更新 更多