How to achieve an android:background
change effect on multiple Views
at the same time, on clicking any of them?
I got a "badge" layout in two parts. They act like one button, but the two parts have different StateListDrawable
(selectors) defining backgrounds for state_pressed
etc. The first part is a header ("lefter") with an image. The second is a content area getting filled with various sub-contents. It all comes down to that the contents of the both parts both come in various sizes.
I want the two badge parts to stretch separately AND share a common background effect when any of them is pressed.
<LinearLayout
style="@style/Badge">
<!-- LEFTER -->
<LinearLayout
style="@style/BadgeLefter"
android:background="@drawable/badge_lefter_bg_blue">
<ImageView
style="@style/BadgeLefterImage"
android:src="@drawable/office_building"/>
</LinearLayout>
<!-- CONTENT -->
<LinearLayout
android:id="@+id/badge_blue_content"
style="@style/BadgeContent"
android:background="@drawable/badge_content_bg_blue">
</LinearLayout>
</LinearLayout>
Example of StateListDrawable
background selector (like @drawable/badge_content_bg_blue
above):
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:state_pressed="false"
android:drawable="@drawable/badge_bg_blue_normal"/>
<item android:state_focused="false" android:state_pressed="true"
android:drawable="@drawable/badge_bg_blue_pressed"/>
<item android:state_focused="true"
android:drawable="@drawable/badge_bg_blue_focused"/>
<item android:state_focused="true" android:state_pressed="true"
android:drawable="@drawable/badge_bg_blue_pressed"/>
</selector>
where badge_bg_blue_normal
etc are 9-patch png's.
I'm new to android. I failed to find a similar question here. It does not help to custom my own Button
because buttons only have one android:background selector
. I found no 9-patch supporting multiple stretchable areas. I realize I could build a custom component. Is that a good idea here?
I use my badges widely around the app. An elegant solution would be greatly appreciated! :)
* SOLUTION EDIT: *
After building a custom component with a TouchListener
I'm all set: ^_^
public class Badge extends LinearLayout {
//...
public Badge(Context c, AttributeSet attrs) {
super(c, attrs);
//...
// inflating layouts and setting selector backgrounds here
//...
setClickable(true);
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
lefter.setPressed(true);
contents.setPressed(true);
}
else if (event.getAction() == MotionEvent.ACTION_UP || !isInside(v, event)) {
lefter.setPressed(false);
contents.setPressed(false);
}
return false;
}
private boolean isInside(View v, MotionEvent event) {
//...
}
});
}
//...
}