Wednesday 23 April 2014

Android - How to Set id for view programatically (findViewById)

Whenever you create view via programming, How can you set ID for each view

First create id for view - 

Go to res/values/Strings.xml

<resources>
      <item type="id" name="my_button" />
     <item type="id" name="my_imgbutton" />
</resources>

Set the id of view in your activity class in OnCreate Method.

Button my_button = new Button(context);
ImageButton my_imgbutton = new ImageButton(context);
my_button .setId(R.id.my_button);
my_imgbutton .setId(R.id.my_imgbutton);
             
Then Find the view using findViewById .  

my_imgbutton= (ImageButton) findViewById(R.id.my_imgbutton);
my_button= (Button) findViewById(R.id.my_button);    

No comments:

Post a Comment