[英]Styling Views created programmatically on Android
所以我正在阅读的家伙们说,根本不可能通过Java设置view
的样式。 尚无此类方法myView.setStyle("styleName")
。
然后,当您通过代码创建布局元素(例如textvews
, imageviews
或linearlayouts
作为容器)时,如何设置它们的样式? 您是否按规则为每个新创建的元素分配规则? 还是有一种更有效的方法来执行此任务?
@编辑
好吧,我知道了怎么做。 用我正在使用的解决方案回答我的问题
每个View或其子类都有一个采用Style参数的第三个构造函数。 例如, 此 View的构造函数。 提及此视图的样式资源ID,因此在创建视图时应提及它。
从文档
应用于此视图的默认样式。 如果为0,则不会应用任何样式(超出主题中的样式)。 这可以是属性资源(其值将从当前主题中检索),也可以是显式样式资源。
您可以将要设置样式的视图子类化,并在运行时传递希望应用的样式。 类似于下面的类,它只是将自定义字体设置为TextView。 主要是,您需要研究可以提供样式的第3个构造函数。
public class TextViewRoboto extends TextView {
public TextViewRoboto(Context context) {
super(context);
}
public TextViewRoboto(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public TextViewRoboto(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
setCustomFont(ctx, "roboto-light.ttf");
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface tf = null;
try {
tf = Typefaces.get(ctx, asset);
} catch (Exception e) {
Logger.e("Could not get typeface: " + e.getMessage());
return false;
}
setTypeface(tf);
return true;
}
}
我找到的解决方案目标是以编程方式创建以前在其他地方设置样式的元素。
首先,我在res / layout文件夹中创建了一个新的XML文件。 我将其命名为template.xml,并在其中插入了以下代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
style="@style/rootElement"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/firstChildId"
style="@style/firstChild" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/secondChild" />
</LinearLayout>
然后我在styles.xml文件中设置了想要的样式
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="rootElement">
<!-- style -->
</style>
<style name="firstChild">
<!-- style -->
</style>
</resources>
现在,在我的Activity类中,添加了:
LinearLayout rootElement = (LinearLayout) getLayoutInflater().inflate(R.layout.template, null);
someOtherView.addView(rootElement);
充气器将加载我们在res / layout / template.xml中创建的模板(该文件中的所有元素及其属性),并将其分配给rootElement
,然后在我的代码中将其用于其他任何事情。 例
TextView firstChild = (TextView) rootElement.getChildAt(0);
firstChild.setText("It is the firstChild element");
要么
TextView firstChild = (TextView) rootElement.findViewById(R.id.firstChildId);
...
很简单,不是吗? 希望对您有所帮助
您可以使用主题和样式
通过在Android清单中指定主题名称,可以将主题应用于整个应用程序
例如<application android:theme="@style/CustomTheme">
您可以通过指定特定样式来覆盖特定活动的主题。
有各种预定义的主题,Holo Light和Holo Dark是较常见的主题。 大多数应用程序都从创建一个继承自上述主题之一的新主题开始,并根据需要覆盖特定元素。
真正最好的办法是参考文档,该文档应该始终是您的第一站。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.