[英]Set view style programmatically Kotlin
我搜索了很多答案,但没有找到任何有效的解决方案。 我想知道是否有可能以编程方式设置 Edittext 样式。 在我的情况下,我有一个布局包含在两个不同的地方并在两个不同的地方使用,并且在包含它的地方旁边需要使用不同的样式。
<style name="TestStyle1" parent="Widget.AppCompat.EditText">
<item name="android:maxLength">1</item>
<item name="android:singleLine">true</item>
</style>
<style name="TestStyle2" parent="CodeTextStyle">
<item name="android:alpha">0.5</item>
</style>
first_activity.xml
<include
layout="@layout/custom_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
second_activity.xml
<include
layout="@layout/custom_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
custom_layout.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CustomEditText
android:id="@+id/et"
app:style_ref="@style/CustomTextStyle"
style="@style/TestStyle1" <-- Here i need to change style beside of usage
android:layout_height="wrap_content" />
</LinearLayout>
自定义编辑文本.kt
class CustomEditText @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : AppCompatEditText(context, attrs) {
init {
val typedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.CustomEditText, 0 , 0)
try {
val style2 = typedArray.getResourceId(R.styleable.CustomEditText_style_ref, 0)
setTypeface(Typeface.DEFAULT, style2)
invalidate()
}
}
}
因此,最简单的方法是,如果您的最小 API 级别为 23,则在相应活动布局膨胀后获取每个 CustomEditText 实例的引用,然后只需设置
myCustomEditText.setTextAppearance(R.style.TestStyle1)
如本答案中所述(使用的是已弃用的版本)
另一种选择是将 2 种样式应用于两个各自的应用主题样式,您可以将其设置为 AndroidManifest 中的每个活动。
或者你可以走我在评论中建议的更复杂的路径:创建一个自定义的 LinearLayout 类并在构造函数中传递样式:
class CustomLayout(context: Context) : LinearLayout(context, null, R.style.TestStyle1)
您只需要想办法让布局知道它创建了哪个活动。 据我所知,该样式将分别传递给每个子视图,即您的 CustomEditText。
两个有用的答案。
RelativeLayout layout = (RelativeLayout)getLayoutInflater().inflate(R.layout.template, null);
或者
int buttonStyle = R.style.your_button_style;
Button button = new Button(new ContextThemeWrapper(context, buttonStyle), null, buttonStyle).
请参阅https://stackoverflow.com/a/24438579/5093308和https://stackoverflow.com/a/5488652/5093308
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.