所以我读到的伙计们,根本不可能view
通过 Java 设置 a 的样式。目前还没有这样的方法myView.setStyle("styleName")
。
那么当你通过代码创建你的布局元素时,比如textvews
, 和imageviews
orlinearlayouts
作为容器,你如何设置它们的样式呢?您是否按每个新创建的元素的规则分配规则?还是有更有效的方法来完成这项任务?
@编辑
好吧,我知道该怎么做了。将用我正在使用的解决方案回答我的问题
所以我读到的伙计们,根本不可能view
通过 Java 设置 a 的样式。目前还没有这样的方法myView.setStyle("styleName")
。
那么当你通过代码创建你的布局元素时,比如textvews
, 和imageviews
orlinearlayouts
作为容器,你如何设置它们的样式呢?您是否按每个新创建的元素的规则分配规则?还是有更有效的方法来完成这项任务?
@编辑
好吧,我知道该怎么做了。将用我正在使用的解决方案回答我的问题
每个 View 或其子类都有第三个构造函数,它接受 Style 参数。比如这个View的构造函数。提及此视图的样式资源 ID,因此应在创建视图时提及。
从文档
应用于此视图的默认样式。如果为 0,则不会应用任何样式(超出主题中包含的样式)。这可能是一个属性资源,其值将从当前主题中检索,也可能是一个显式样式资源。
您可以对要设置样式的视图进行子类化,并传递您希望在运行时应用的样式。类似于下面的类,它只是将自定义字体设置为 TextView。主要是,您需要查看可以提供样式的第三个构造函数。
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 是更常见的主题。大多数应用程序首先创建一个从上述主题之一继承的新主题,并根据需要覆盖特定元素。
真正要做的最好的事情是参考文档,它应该始终是您的第一站。