gpt4 book ai didi

Android:以编程方式设置 View 样式

转载 作者:IT老高 更新时间:2023-10-28 12:53:14 25 4
gpt4 key购买 nike

这是 XML:

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/LightStyle"
android:layout_width="fill_parent"
android:layout_height="55dip"
android:clickable="true"
android:orientation="horizontal" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />

</RelativeLayout>

如何以编程方式设置 style 属性?

最佳答案

从技术上讲,您可以通过自定义 View 以编程方式应用样式:

private MyRelativeLayout extends RelativeLayout {
public MyRelativeLayout(Context context) {
super(context, null, R.style.LightStyle);
}
}

单参数构造函数是在以编程方式实例化 View 时使用的构造函数。

因此,将此构造函数链接到接受样式参数的 super。

RelativeLayout someLayout = new MyRelativeLayout(new ContextThemeWrapper(this,R.style.RadioButton));

或者正如@Dori 简单指出的那样:

RelativeLayout someLayout = new RelativeLayout(new ContextThemeWrapper(activity,R.style.LightStyle));

现在在 Kotlin 中:

class MyRelativeLayout @JvmOverloads constructor(
context: Context,
attributeSet: AttributeSet? = null,
defStyleAttr: Int = R.style.LightStyle,
) : RelativeLayout(context, attributeSet, defStyleAttr)

 val rl = RelativeLayout(ContextThemeWrapper(activity, R.style.LightStyle))

关于Android:以编程方式设置 View 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11723881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com