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
?
ベストアンサー1
技術的には、カスタム ビューを使用してプログラムでスタイルを適用できます。
private MyRelativeLayout extends RelativeLayout {
public MyRelativeLayout(Context context) {
super(context, null, R.style.LightStyle);
}
}
1 つの引数を持つコンストラクターは、プログラムでビューをインスタンス化するときに使用されます。
したがって、このコンストラクターを、スタイル パラメーターを受け取るスーパーに連結します。
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))