Felix
Felix

Reputation: 89576

Android: change TextView textColor when parent is focused

I have a TextView inside a LinearLayout. The LinearLayout is able to receive focus, and I want the textColor of the TextView to change when it does. I thought using a ColorStateList would work, but it would seem that the TextView does not receive focus when the LinearLayout does. 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. The reason for that is because in another activity I have an ExpandableListView with a custom adapter and custom views and Android changes the textColors of the TextViews (from light to dark) inside my custom views when items are focused.

Upvotes: 10

Views: 6258

Answers (2)

Antoine
Antoine

Reputation: 166

This is an old post, but since I had the same problem, here is the XML attribute I found to do this :

android:duplicateParentState="true"

(to be added to the TextView to change its "focused" state when the Layout's state changes)

Upvotes: 14

Bostone
Bostone

Reputation: 37126

You can fetch yout TextView in the onFocuseChange method of LinearLayout's listener. 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

Upvotes: 4

Related Questions