Event from button in android

Buttons

A button consists of text or an icon (or both text and an icon) that communicates what action occurs when the user touches it.

Depending on whether you want a button with text, an icon, or both, you can create the button in your layout in three ways:

  • With text, using the Button class:
  • With an icon, using the ImageButton class:
  • With text and an icon, using the Button class with the android:drawableLeft attribute:

Key classes are the following:

Responding to Click Events

When the user clicks a button, the Button object receives an on-click event.

To define the click event handler for a button, add the android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

For example, here’s a layout with a button using android:onClick :

Within the Activity that hosts this layout, the following method handles the click event:

Kotlin

The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:

  • Be public
  • Return void
  • Define a View as its only parameter (this will be the View that was clicked)

Using an OnClickListener

You can also declare the click event handler programmatically rather than in an XML layout. This might be necessary if you instantiate the Button at runtime or you need to declare the click behavior in a Fragment subclass.

To declare the event handler programmatically, create an View.OnClickListener object and assign it to the button by calling setOnClickListener(View.OnClickListener) . For example:

Kotlin

Styling Your Button

The appearance of your button (background image and font) may vary from one device to another, because devices by different manufacturers often have different default styles for input controls.

You can control exactly how your controls are styled using a theme that you apply to your entire application. For instance, to ensure that all devices running Android 4.0 and higher use the Holo theme in your app, declare android:theme=»@android:style/Theme.Holo» in your manifest’s element. Also read the blog post, Holo Everywhere for information about using the Holo theme while supporting older devices.

To customize individual buttons with a different background, specify the android:background attribute with a drawable or color resource. Alternatively, you can apply a style for the button, which works in a manner similar to HTML styles to define multiple style properties such as the background, font, size, and others. For more information about applying styles, see Styles and Themes.

Borderless button

One design that can be useful is a «borderless» button. Borderless buttons resemble basic buttons except that they have no borders or background but still change appearance during different states, such as when clicked.

To create a borderless button, apply the borderlessButtonStyle style to the button. For example:

Читайте также:  Что такое ant hal service android что это

Custom background

If you want to truly redefine the appearance of your button, you can specify a custom background. Instead of supplying a simple bitmap or color, however, your background should be a state list resource that changes appearance depending on the button’s current state.

You can define the state list in an XML file that defines three different images or colors to use for the different button states.

To create a state list drawable for your button background:

    Create three bitmaps for the button background that represent the default, pressed, and focused button states.

To ensure that your images fit buttons of various sizes, create the bitmaps as Nine-patch bitmaps.

Источник

Android: выдвигающийся экран снизу

Данная статья является переводом статьи Emrullah Luleci, а также её продолжения.

Нижний экран (Здесь и далее под «нижним экраном/слоем» будет подразумеваться элемент bottom sheet — прим. пер.) — компонент, выезжающий снизу экрана, который используется для отображения дополнительного контента. Подробнее об этом элементе можно узнать на официальной сайте посвященном материальному дизайну.

Зависимости

Для использования этого элемента, добавьте последние версии библиотек поддержки в свой проект:

Создайте класс наследник от AppCompatActivity:

Создание макетов

Содержимое нижнего экрана

Для удобства воспользуемся макетами. Назовем файл с нижним слоем bottom_sheet.xml.

behavior_peekHeight: Определяет высоту видимой части.

behavior_hideable: Определяет, может ли нижний экран скрываться свайпом вниз.

Container view

Создайте CoordinatorLayout в качестве корневого вью. Добавьте в него прямым наследником bottom_sheet.xml. Элементы app_bar и activity_bottom_sheet_content не имеют прямого отношения к нижнему экрану, поэтому их можно заменить или удалить.

На данном этапе нижний экран должен работать примерно так:

Динамическое управление

Поведением и свойствами нижнего экрана можно также управлять динамически с помощью Java.

Прикрепление элементов к нижнему экрану

Также можно прикрепить вью к нижнему экрану, чтобы прикрепленный элемент перемещался одновременно с нижним слоем.

Добавим Floating Action Button в макет созданный выше. Новый компонент должен являться непосредственным наследником CoordinatorLayout также как и bottom_sheet. Для прикрепления элемента к нижнему экрану необходимо добавить app:layout_anchor с id вью нижнего экрана, а также app:layout_anchorGravity со значением top|end.

Теперь плавающая кнопка закреплена в верхнем углу нашего нижнего экрана и перемещается вместе с ним.

Скрытие плавающей кнопки при скроле

Для скрытия кнопки при скроле необходимо добавить слушатель к нижнему экрану и отображать/скрывать кнопку. Для начала найдем необходимые вью:

Для скрытия кнопки в момент начала скрола и отображения после полного сворачивания нижнего экрана, используйте следующее:

Результат обоих вариантов можно увидеть ниже:

Источник

Technology Talks

on Microsoft technologies, Web, Android and others

Android : Using Button & Click-Event with example

Introduction :

In this article we will learn, how to use Button and Listen for Click-Events. We shall take an example to understand all these . To make the example clear and easy to understand we shall use another control called EditText.

Implementation using Example :

  • Create a new android project with name ButtonTutorial.
    [If you are a beginner and don’t know how to create a project then read it here Creating HelloWorld Application in Android]
  • Type you application name as My Button Tutorial.
  • Provide package name as com.suvendu.tutorials.button
  • Open main.xml and delete the single TextView already present in the page(may be with a text ‘Hello World, ButtonTutorialActivity!’.
  • Drag a EditText and a Button on to the layout.
  • Change the id of the EditText to ‘@+id/txtShowCurTime
  • Change the id of the Button to ‘@+id/btnGenCurTime
  • Add a new string to strings.xml with Name‘button’ and ValueGenerate Current Time
  • Change the text of the Button to ‘@string/button’
    [Your layout is ready now and the main.xml should look like this]
Читайте также:  Андроид как сделать автодозвон
  • Open your default activity file (Ex: ButtonTutorialActivity.java)
  • Declare two global variables
  • import respective packages
  • Link these variables to the layout in OnCreate() as follows
  • We don’t want the OnScreenKeyBoard to appear when the cursor is on EditText so, let disable this.
  • import the package for OnClickListener
  • Now do the logic inside onClick() to show the current time
  • You need to import java package for using Date
  • Finally, the default activity file should look like
  • Downloads :

    You can download the full project here.

    Or, you can just download the apk here.

    Conclusion :

    We are able to use a Button control in Android and can use its OnClick event to do various activities.
    I hope you enjoyed this tutorial.

    Please give your valuable feedback and stay tuned for more ..

    You may also like-

    If you are a beginner then you may also like following articles-

    Источник

    Event from button in android

    In Android, Button represents a push button. A Push buttons can be clicked, or pressed by the user to perform an action. There are different types of buttons used in android such as CompoundButton, ToggleButton, RadioButton.

    Button is a subclass of TextView class and compound button is the subclass of Button class. On a button we can perform different actions or events like click event, pressed event, touch event etc.

    Android buttons are GUI components which are sensible to taps (clicks) by the user. When the user taps/clicks on button in an Android app, the app can respond to the click/tap. These buttons can be divided into two categories: the first is Buttons with text on, and second is buttons with an image on. A button with images on can contain both an image and a text. Android buttons with images on are also called ImageButton.

    Button code in XML:

    The below code will create Button and write “Abhi Android” text on it.

    Table Of Contents

    Attributes of Button in Android:

    Now let’s we discuss some important attributes that helps us to configure a Button in your xml file (layout).

    1. id: id is an attribute used to uniquely identify a text Button. Below is the example code in which we set the id of a Button.

    2. gravity: The gravity attribute is an optional attribute which is used to control the alignment of the text like left, right, center, top, bottom, center_vertical, center_horizontal etc.

    Below is the example code with explanation included in which we set the right and center vertical gravity for text of a Button.

    3. text: text attribute is used to set the text in a Button. We can set the text in xml as well as in the java class.

    Below is the example code with explanation included in which we set the text “Learning Android @ AbhiAndroid” in a Button.

    Setting Text Using Java class:

    Below is the example code in which we set the text on Button programmatically means in java class. The output will be same as the above.

    4.textColor: textColor attribute is used to set the text color of a Button. Color value is in the form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.

    Читайте также:  Как удалить ярлык с рабочего стола андроида

    Below is the example code with explanation included in which we set the red color for the displayed text of a Button.

    Setting Text Color On Button Inside Java class:

    Below is the example code in which we set the text color of a Button programmatically means in java class.

    5. textSize: textSize attribute is used to set the size of the text on Button. We can set the text size in sp(scale independent pixel) or dp(density pixel).

    Below is the example code in which we set the 25sp size for the text of a Button.

    Setting textSize In Java class:

    Below is the example code in which we set the text size of a Button programmatically means in java class.

    6. textStyle: textStyle attribute is used to set the text style of a Button. The possible text styles are bold, italic and normal. If we need to use two or more styles for a Button then “|” operator is used for that.

    Below is the example code with explanation included, in which we set the bold and italic text styles for text of a button.

    7. background: background attribute is used to set the background of a Button. We can set a color or a drawable in the background of a Button.

    Below is the example code in which we set the gren color for the background, Black color for the displayed text and set 15dp padding from all the side’s for Button.

    Setting background in Button In Java class:

    Below is the example code in which we set the background color of a Button programmatically means in java class.

    8. padding: padding attribute is used to set the padding from left, right, top or bottom. In above example code of background we also set the 10dp padding from all the side’s of button.

    9. drawableBottom: drawableBottom is the drawable to be drawn to the below of the text.

    Below is the example code in which we set the icon to the below of the text.

    Make sure you have image saved in your drawable folder name ic_launcher.

    10. drawableTop, drawableRight And drawableLeft: Just like the above attribute we can draw drawable to the left, right or top of text.

    In the Below example we set the icon to the right of the text. In the same way you can do for other two attribute by your own:

    Button Example In Android Studio:

    Below is the example of button in which we display two buttons with different background and whenever a user click on the button the text of the button will be displayed in a toast.

    Step 1: Create a new project in Android Studio and name it ButtonExample.

    Step 2: Now open res -> layout -> xml (or) activity_main.xml and add following code. Here we are designing the UI of two button in Relative Layout.

    Step 3: Now Open app -> package -> MainActivity.java and the following code. Here using setOnClickListener() method on button and using Toast we will display which button is clicked by user.

    Output:

    Now start the AVD in Emulator and run the App. You will see two button. Click on any button and you will see the message on screen which button is clicked.

    Источник

    Оцените статью