How would I model a follow/unfollow button in Android? Is State List Drawable what I am looking for? How can define the two different states?
This is highly dependant on the visual effect you want to achieve.
First, the basics (I assume you already know this): you need a Button
, setOnClickListener()
for a listener that toggles the state, and someplace to save this (either a local database, your own server, or whatever).
The easiest, least attractive way, would be to just switch the text on the button whenever the "follow" state changes (with setText()
in the click listener).
A possible improvement would be to have different button backgrounds, so that the appearance also changes (say, from a grey star to a yellow one). For this, you just need to call setBackground()
in the click listener.
For a fancier effect, you can use a TransitionDrawable
to crossfade this change. startTransition()
and reverseTransition()
would then be used for the two state changes. For example:
Drawable d1 = getResources().getDrawable(R.drawable.follow_button);
Drawable d2 = getResources().getDrawable(R.drawable.unfollow_button);
final TransitionDrawable followDrawable = new TransitionDrawable(new Drawable[] { d1, d2 });
final int transitionDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);
button.setBackground(followDrawable);
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if (!mFollowing)
{
mFollowing = true;
followDrawable.startTransition(transitionDuration);
}
else
{
mFollowing = false;
followDrawable.reverseTransition(transitionDuration);
}
}
});