What is the best way to add a button?

I am new to Android development. I have doubts. I know that you can add a button and initialize it as

Button b1=(Button) findViewById(R.id.button1);

and I can also give the name a name in the XML file.

  android:onClick="click_event"

I doubt this is the best and most effective way? as he says it's better to use the @string resource instead of hard-coded.

+3
source share
1 answer

I think you are confused. The examples you give are two different things.

Adding a Button

This line

Button b1=(Button) findViewById(R.id.button1);

does not add a Button. It declares and initializes an instance Buttonthat references Buttonin the current bloated xml, which has idofbutton1

So in your xml would you go somewhere

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

Button

Button bt1 = new Button(this);
// give it properties

xml , , layout

OnClick

onClick(), , . xml, , . , , , public , View

 public void clickEvent(View v)
{
    // code here
}

, xml

<Button
     android:id="@+id/button1"
     <!-- other properties -->
     android:onClick="clickEvent"/>

onClick() Java -

Button b1=(Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        // code here
    }
});

 Button b1=(Button) findViewById(R.id.button1);
b1.setOnClickListener(this);

    @Override
    public void onClick(View v)
    {
        // code here
    }

, implements OnClickListener Activity

public class MyActivity extends Activity implements OnClickListener
{

Listener, -

b1.setOnClickListener(myBtnClick);

-

public OnClickListener myBtnClick = new OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        // click code here      
    }
};

Button id View, , Button Listeners Button s.

+9

All Articles