Can anybody tell how to add a button in android?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
Check this Android Button tutorial; this simple example creates a Close Button.
All you need to do is:
1.Add Button widget to your Layout
2.Attach a setOnClickListener method to the button instance:
Adding a Button
doesn't add a Button. It declares and initializes an instance of Button which refers to a Button in your currently inflated xml which has an id of button1
So in your xml you would have somewhere
You can add a Button programmatically with
But it is generally easier to do in xml because here you have to programmatically give it parameters, properties, and add it to an inflated layout
OnClick
As far as the onClick() it depends on what you feel is the easiest and best in your situation. I like to declare it in the xml like that often but you can do it several ways. Using this method you just have to be sure that you have a function like this that is public and takes only one parameter and that parameter must be a View
I also changed the name so your xml would be like
You also can set onClick() in your Java with something like
or
Note that the last way you will need to add implements OnClickListener in your Activity declaration
You can also create your own click Listener by changing it to something like
then create an instance of it with something like
You can use this for multiple Buttons and switch on the id or check the View param to know which Button was clicked or create separate Listeners for different Buttons.
Dynamic:
According to official documentation of Buttons provided by Android. You can first create Button in your
.xml
file.Button.xml
And then cast your button with Button Class and set ClickListener.
For further detail you can visit this link