views:

1630

answers:

2

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.

+2  A: 

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

DroidIn.net
I know I can do it that way, but as I said in the original post, I would like to avoid it. Also, if you have ever used a custom adapter for a ListView you would see that it still changes the text color when focusing a list item, no matter how many elements you have inside an item view. I'm curious how they did that, and I'll bet it's done from XML only.
Felix
+1  A: 

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)

Antoine