[英]Android: change TextView textColor when parent is focused
I have a TextView
inside a LinearLayout
. 我在
LinearLayout
有一个TextView
。 The LinearLayout
is able to receive focus, and I want the textColor
of the TextView
to change when it does. LinearLayout
能够接收焦点,我希望TextView
的textColor
在它发生时改变。 I thought using a ColorStateList would work, but it would seem that the TextView
does not receive focus when the LinearLayout
does. 我认为使用ColorStateList会起作用,但看起来,当
LinearLayout
执行时, TextView
不会获得焦点。 I know that, because I have tried this code: 我知道,因为我尝试过这段代码:
mTextView.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
Log.d(TAG, "Changed TextView focus to: " + hasFocus);
}
});
And nothing gets logged. 没有任何记录。 I don't want to use an
OnFocusChangeListener
on the LinearLayout to change the textColor
of the TextView
, I think this has to be done from XML. 我不想在LinearLayout上使用
OnFocusChangeListener
来更改TextView
的textColor
,我想这必须从XML完成。 The reason for that is because in another activity I have an ExpandableListView
with a custom adapter and custom views and Android changes the textColor
s of the TextView
s (from light to dark) inside my custom views when items are focused. 原因是因为在另一个活动中我有一个带有自定义适配器和自定义视图的
ExpandableListView
,当项目被聚焦时,Android会在我的自定义视图中更改TextView
的textColor
(从亮到暗)。
This is an old post, but since I had the same problem, here is the XML attribute I found to do this : 这是一个旧帖子,但由于我遇到了同样的问题,这里是我发现的XML属性:
android:duplicateParentState="true"
(to be added to the TextView to change its "focused" state when the Layout's state changes) (当布局状态发生变化时,添加到TextView以更改其“聚焦”状态)
You can fetch yout TextView in the onFocuseChange method of LinearLayout's listener. 您可以在LinearLayout的侦听器的onFocuseChange方法中获取TextView。 Something like
就像是
public void onFocusChange(View v, boolean hasFocus) {
TextView tv = (TextView)v.findViewById(R.id.myTextView);
tv.setTextColor(R.color.foo);
}
Since your LL can host multiple widgets I think it's expected that onFocus of the LL will not propagate even if you have a single control 由于您的LL可以托管多个小部件,我认为即使您只有一个控件,LL的onFocus也不会传播
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.