android - Which is the best way to add a button? -


i'm new android development. i've doubt. know can add button , initialize like

button b1=(button) findviewbyid(r.id.button1); 

and can give unction name in xml file.

  android:onclick="click_event" 

my doubt is, best , efficient way? says better use @string resource instead of hard-coded one.

i think confused. examples give 2 different things.

adding button

this line

button b1=(button) findviewbyid(r.id.button1); 

doesn't add button. declares , initializes instance of button refers button in inflated xml has id of button1

so in xml have somewhere

<button      android:id="@+id/button1"      <!-- other properties --> /> 

you can add button programmatically

button bt1 = new button(this); // give properties 

but easier in xml because here have programmatically give parameters, properties, , add inflated layout

onclick

as far onclick() depends on feel easiest , best in situation. declare in xml can several ways. using method have sure have function public , takes 1 parameter , parameter must view

 public void clickevent(view v) {     // code here } 

i changed name xml like

<button      android:id="@+id/button1"      <!-- other properties -->      android:onclick="clickevent"/> 

you can set onclick() in java like

button b1=(button) findviewbyid(r.id.button1); b1.setonclicklistener(new onclicklistener() {     @override     public void onclick(view v)     {         // code here     } }); 

or

 button b1=(button) findviewbyid(r.id.button1); b1.setonclicklistener(this);      @override     public void onclick(view v)     {         // code here     } 

note last way need add implements onclicklistener in activity declaration

public class myactivity extends activity implements onclicklistener { 

you can create own click listener changing like

b1.setonclicklistener(mybtnclick); 

then create instance of like

public onclicklistener mybtnclick = new onclicklistener() {     @override     public void onclick(view v)     {         // click code here           } }; 

you can use multiple buttons , switch on id or check view param know button clicked or create separate listeners different buttons.


Comments

Popular posts from this blog

java - How to Configure JAXRS and Spring With Annotations -

visual studio - TFS will not accept changes I've made to a Java project -

php - Create image in codeigniter on the fly -