I have a linearLayout with buttons as its children. I need the button backgrounds to change when they get focus. The buttons are focusable in touch mode.
I have set the following selector xml to the buttons.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:drawable="@drawable/tile_focused" />
<item android:drawable="@drawable/tile" /> <!-- default -->
</selector>
Update
if (layout == null) {
layout = new LinearLayout(this);
RelativeLayout.LayoutParams rlp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
rlp.addRule(RelativeLayout.BELOW, R.id.toplogo);
layout.setLayoutParams(rlp);
layout.setId(wordLayoutID);
layout.setBackgroundColor(Color.WHITE);
mainLayout.addView(layout, rlp);
}
Drawable tileBG = getResources().getDrawable(R.drawable.selector_tile);
for (int i = 0; i < word.length(); i++) {
Button btntile = new Button(this);
LinearLayout.LayoutParams rlp = new LinearLayout.LayoutParams(40, 40);
btntile.setId(inputViewsIds+i);
btntile.setBackgroundDrawable(tileBG);
btntile.setFocusableInTouchMode(true);
layout.addView(btntile, rlp);
}
The problem is that when I set focus to any one button, all button’s backgrounds change to “tile_focused”.
I guess the problem is in the selector xml. What is wrong here?
The root cause of this behavior was the common tile drawable reference I used for all buttons. I changed that and loaded separate drawables for each button. That fixed it.
Thanks to Everyone.