【问题标题】:Cannot set style to LinearLayout programmatically无法以编程方式将样式设置为 LinearLayout
【发布时间】:2019-03-17 13:17:50
【问题描述】:

我正在尝试以这种方式将样式设置为以编程方式创建的 LinearLayout:

(参考:Android: set view style programmatically

LinearLayout linearLayout = new LinearLayout(this, null, R.style.linear_container);

还有styles.xml

<style name="linear_container">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_marginBottom">20dp</item>
    <item name="android:background">#9B1212</item>
    <item name="android:orientation">vertical</item>
</style>

但是样式没有应用如何使它工作?

【问题讨论】:

  • 无法解析符号 ContextThemeWrapper
  • 正在工作,但边距、宽度和高度未设置!!
  • 那么如何以编程方式为项目添加边距?我尝试了很多解决方案,但对我没有任何帮助。你能帮我解决这个问题吗?
  • 这里添加了问题请看stackoverflow.com/questions/55207828/…

标签: android styles android-linearlayout programmatically-created


【解决方案1】:

您可以设置布局参数如下:

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
         LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    layoutParams.setMargins(10, 10, 10, 10);
    linearLayout.setLayoutParams(layoutParams);

【讨论】:

  • @PHP 用户知道了吗?
  • @PHP 用户有任何疑问?
【解决方案2】:

以编程方式设置样式的更简单方法是使用 Airbnb 的 paris 库。 正确实现库后,就像

myView.style(R.style.MyStyle)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 2012-04-12
    相关资源
    最近更新 更多