Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 330
Felix Avatar asked Oct 17 '09 13:10

Felix


2 Answers

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)

like image 85
Antoine Avatar answered Nov 18 '22 04:11

Antoine


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

like image 34
Bostone Avatar answered Nov 18 '22 06:11

Bostone