Programming/Non programming

Tuesday, March 23, 2010

Android:setTag() and getTag() usage for changing the controls..

Android:

setTag() and getTag() usage for changing the controls..

When we are in a situation to dynamically change something on the controls(for example), we can use setTag() and getTag() to identify which one needs to be chosen.

For example:

When i was need to change the background image for the buttons dynamically one to another, i might need to use such techniques. Here is a example code below..

Concept: When "touching" on a button, button should change the current background image to next background image. When again clicking on same button, should change the background image to previous one.
ImageButton button1;
ImageButton button2;
private int firstImgId = 0;
private int secondImgId = 0;

// setting up buttons background image..
private void setBackButtonImage()
{
Log.d("mysample", "Set back button images");
button1 = (ImageButton) findViewById(R.id.ImageButton01);
button2 = (ImageButton) findViewById(R.id.ImageButton02);
// set touch listener for buttons
button1.setOnTouchListener(this);
button2.setOnTouchListener(this);

firstImgId = R.drawable.myFirstImage;
secondImgId = R.drawable.mySecondImage;

// setting the proper images in the background.
button1.setImageResource(firstImgId);
button1.setTag("1");

button2.setImageResource(secondImgId);
button2.setTag("2");
}
public boolean onTouch(View v, MotionEvent event) 
{
ImageButton imgBtn = (ImageButton) v;
if ( imgBtn==button1 ) // first button touch
{
if ( button1.getTag()=="1" )
{
button1.setImageResource(R.drawable.myFirstImage);
button1.setTag("2");
}
else
{
button1.setImageResource(R.drawable.mySecondImage);
button1.setTag("1");
}
}
else if ( imgBtn==button2 ) // second button touch
{
if ( button2.getTag()=="1" )
{
button2.setImageResource(R.drawable.myFirstImage);
button2.setTag("2");
}
else
{
button2.setImageResource(R.drawable.mySecondImage);
button2.setTag("1");
}
}

}


That's it, you got go !!!


Thank you for followers!

Cheers,

M.P.Prabakar
Senior Systems Analyst.

Have fun and be addictive by playing "TossRing" marvelous iPhone game. Link is below..