简体   繁体   English

样式化在Android上以编程方式创建的视图

[英]Styling Views created programmatically on Android

So guys I was reading that it's simply not possible to set the style of a view via Java. 所以我正在阅读的家伙们说,根本不可能通过Java设置view的样式。 There is no such method myView.setStyle("styleName") yet. 尚无此类方法myView.setStyle("styleName")

Then when you create your layout elements by code, such as textvews , and imageviews or linearlayouts as containers, how do you set their style? 然后,当您通过代码创建布局元素(例如textvewsimageviewslinearlayouts作为容器)时,如何设置它们的样式? Do you assign rule by rule of each newly created element? 您是否按规则为每个新创建的元素分配规则? Or is there a more efficient way to do this task? 还是有一种更有效的方法来执行此任务?

@EDIT @编辑

Alright, I figured out how do it. 好吧,我知道了怎么做。 Will answer my question with the solution I'm using 用我正在使用的解决方案回答我的问题

Each View or its subclass has a third constructor that take the Style argument. 每个View或其子类都有一个采用Style参数的第三个构造函数。 For example, this constructor of View. 例如, View的构造函数。 Mention the Style resource id for this view and thus it should be mentioned during view creation. 提及此视图的样式资源ID,因此在创建视图时应提及它。

From documentation 从文档

The default style to apply to this view. 应用于此视图的默认样式。 If 0, no style will be applied (beyond what is included in the theme). 如果为0,则不会应用任何样式(超出主题中的样式)。 This may either be an attribute resource, whose value will be retrieved from the current theme, or an explicit style resource. 这可以是属性资源(其值将从当前主题中检索),也可以是显式样式资源。

You can subclass the view you want to style and pass the style you wish to apply during runtime. 您可以将要设置样式的视图子类化,并在运行时传递希望应用的样式。 Something like the below class which simply sets a custom font to TextView. 类似于下面的类,它只是将自定义字体设置为TextView。 Mainly, you need to look into the 3rd constructor where you can supply your style. 主要是,您需要研究可以提供样式的第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;
    }

}

The solution I found The goal is to create elements programmatically that were previously styled somewhere else. 我找到的解决方案目标是以编程方式创建以前在其他地方设置样式的元素。

First, I created a new XML file in the res/layout folder. 首先,我在res / layout文件夹中创建了一个新的XML文件。 I named it template.xml and inserted the following code in it: 我将其命名为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>

And then I styled then the way I wanted in styles.xml file 然后我在styles.xml文件中设置了想要的样式

<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="rootElement">
        <!-- style -->          
    </style>

    <style name="firstChild">
        <!-- style -->     
    </style>
</resources>

Now, in my Activity class I added: 现在,在我的Activity类中,添加了:

LinearLayout rootElement = (LinearLayout) getLayoutInflater().inflate(R.layout.template, null);
someOtherView.addView(rootElement);

The inflater will load the template we created in res/layout/template.xml (all the elements in that file and its attributes) and assign it to rootElement that is then used in my code for anything else. 充气器将加载我们在res / layout / template.xml中创建的模板(该文件中的所有元素及其属性),并将其分配给rootElement ,然后在我的代码中将其用于其他任何事情。 Example

TextView firstChild = (TextView) rootElement.getChildAt(0);
firstChild.setText("It is the firstChild element");

or 要么

TextView firstChild = (TextView) rootElement.findViewById(R.id.firstChildId);
...

Quite easy, isn't it?! 很简单,不是吗? I hope that helps 希望对您有所帮助

You can use themes and styles 您可以使用主题和样式

A theme can be applied to the whole application by specifying the name of the theme in the Android manifest 通过在Android清单中指定主题名称,可以将主题应用于整个应用程序

eg <application android:theme="@style/CustomTheme"> 例如<application android:theme="@style/CustomTheme">

You can override the theme for a specific activity by specifying a specific style. 您可以通过指定特定样式来覆盖特定活动的主题。

There are various predefined themes Holo Light and Holo Dark are the more common themes. 有各种预定义的主题,Holo Light和Holo Dark是较常见的主题。 Most apps start by creating a new theme that is inherited from one of the above themes and overriding specific elements as needed. 大多数应用程序都从创建一个继承自上述主题之一的新主题开始,并根据需要覆盖特定元素。

The best thing to do really is to refer to the documentation, which should always be your first port of call. 真正最好的办法是参考文档,该文档应该始终是您的第一站。

http://developer.android.com/guide/topics/ui/themes.html http://developer.android.com/guide/topics/ui/themes.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM