0

I have some Views in my Activity that I inflate and populate at runtime.

The View itself is a RelativeLayout to which I add at runtime several TextViews.

When the View is selected I change the color of the background (and that is easy).

Now I need to change the color of all the TextViews inside the View.

Please how do I do that?

Consider that I do not have a reference to the TextViews themselves, since they are created at runtime, nor do I know how many are in there.

4

2 回答 2

2

考虑到我没有对 TextViews 本身的引用

由于您“在运行时添加了几个 TextViews”,因此当然欢迎您“参考 TextViews 本身”。在您“在运行时添加”时将它们添加到某种集合(例如,ArrayList<TextView>),然后遍历集合以更改它们的颜色。

于 2013-08-31T16:36:57.310 回答
1

您可以通过其他方式执行此操作:

遍历 RelativeLayout 的所有子项(您有参考):

for (int i = 0; i < mRelativeLayout.getChildCount(); i++) {
    if (mRelativeLayout.getChildAt(i) instanceof TextView) {

        // Set text color
        ((TextView)(rl.getChildAt(i))).setTextColor(Color.RED);
    }
}

小心点mRelativeLayout.get(i) instanceof TextView。这将返回由TextView 的子类返回true的所有视图。例如,如果你有一个 Button 内部,将返回,因为 Button 扩展了 TextView。为避免这种情况,请使用:mRelativeLayout.getChildAt(i) mRelativeLayoutinstanceoftrue

if (mRelativeLayout.getChildAt(i) instanceof TextView && 
                                !(mRelativeLayout.getChildAt(i) instanceof Button))
于 2013-08-31T18:09:16.933 回答