为包含的布局android指定文本颜色

时间:2016-11-30 15:54:37

标签: android android-layout

我有一个用于不同地方的布局。

这个布局本身有一个文本视图,一些按钮和一个进度条。

<LinearLayout id="reuse">
  <TextView/>
  <ProgressBar/>
  <Buttons/>
</LinearLayout>

// in other places

<include layout="reuse"/> // text color blue here

// in other places

<include layout="reuse" /> //text color gree here

现在,根据布局的位置,我想为textview指定不同的文本颜色。

如何做到这一点?我尝试在include中指定textcolor似乎没有帮助?

2 个答案:

答案 0 :(得分:1)

我能想到这样做的唯一方法是以编程方式,只需使用线性布局“重用”的引用,并使用reuse.findViewById()从中获取textview并自行操作属性。

答案 1 :(得分:0)

你无法通过xml文件制作,但你可以间接实现这一点。

第一个选项:

您可以通过编程方式执行此操作。例如:

 private void setTextColors(ViewGroup viewGroup) {
    for (int i = 0; i < viewGroup.getChildCount(); i++) {
        View view = viewGroup.getChildAt(i);
        if (view instanceof TextView) {
            ((TextView) view).setTextColor(ContextCompat.getColor(this, android.R.color.holo_blue_bright));
        } else if (view instanceof Button) {
            ((Button) view).setTextColor(ContextCompat.getColor(this, android.R.color.holo_blue_bright));
        }else if (view instanceof EditText) {
            ((EditText) view).setTextColor(ContextCompat.getColor(this, android.R.color.holo_blue_bright));
        } else if (view instanceof LinearLayout) {
            setTextColors((LinearLayout) view);
        }else if (view instanceof RelativeLayout) {
            setTextColors((RelativeLayout) view);
        }else if (view instanceof FrameLayout) {
            setTextColors((FrameLayout) view);
        }
    }

}
  

注意:此方法是一个简单的工作示例。您可以根据需要进行修改。

调用此方法时,将参数作为父布局(如LinearLayout)。在循环中,检查父视图的每个子视图,如果它们是Button,TextView或EditText的实例,则设置所需的颜色。还递归设置子视图组的颜色,例如:

<LinearLayout >
  <TextView/>
  <ProgressBar/>
  <Button/>
  <RelativeLayout>
    <TextView/>
    <ProgressBar/>
    <Button/>
  </LinearLayout>
</LinearLayout>

第二个选项:

您可以在styles.xml文件中为textViews创建样式,并将文本颜色添加到此样式中。 之后,您只需要在布局xml中将样式设置为TextView。

例如:

<TextView
    style="@style/CodeFont"
    android:text="@string/hello" />

<强> styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="CodeFont" parent="@android:style/TextAppearance.Medium">
        <item name="android:textColor">#00FF00</item>
    </style>
</resources>