Button from image android

ImageButton (Кнопка-изображение)

Общая информация

Находится в разделе Buttons.

Компонент ImageButton представляет собой кнопку с изображением (вместо текста). По умолчанию ImageButton похож на обычную кнопку.

В режиме дизайна изображение на кнопке определяется атрибутом android:src

Можно сделать двойной щелчок, чтобы сразу установить нужное свойство.

Методы

Программно можно установить изображения через различные методы.

setImageBitmap() Используется, чтобы указать в качестве изображения существующий экземпляр класса Bitmap setImageDrawable() Используется, чтобы указать в качестве изображения существующий экземпляр класса Drawable setImageResource() Используется, чтобы указать в качестве изображения существующий идентификатор ресурса (см. пример) setImageURI() Используется, чтобы указать в качестве изображения существующий адрес типа Uri. В некоторых случаях элемент кэширует изображение и после изменения изображения по прежнему выводит старую версию. Рекомендуется использовать инструкцию setImageURI(null) для сброса кэша и повторный вызов метода с нужным Uri

Примеры

С помощью метода setImageURI() можно обратиться к ресурсу типа Drawable по его идентификатору:

Например, можно задать путь Uri:

Можно обратиться к ресурсу по его типу/имени:

В этом случае код будет следующим:

Щелчок

Как и у обычной кнопки, интерес представляет только щелчок. В нашем примере мы будем менять поочередно картинки на кнопке (нужно подготовить две картинки в папке drawable)

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

Продолжительное нажатие

Кроме обычного щелчка, в Android есть особый вид нажатия на кнопку — продолжительное нажатие. Это событие происходит, когда пользователь нажимает и удерживает кнопку в течение одной секунды. Этот тип нажатия обрабатывается независимо от обычного щелчка.

Для обработки продолжительного нажатия нужно реализовать класс View.OnLongClickListener и передать его в метод setOnLongClickListener(). Класс OnLongClickListener имеет один обязательный метод OnLongClick(). В принципе это похоже на метод OnClick(), только имеет возвращаемое значение.

Запустите проект и убедитесь, что при быстром нажатии ничего не происходит, а при более продолжительном нажатии всплывает сообщение.

Источник

Android ImageButton with Examples

In android, Image Button is a user interface control that is used to display a button with an image and to perform an action when a user clicks or taps on it.

By default, the ImageButton looks same as normal button and it performs an action when a user clicks or touches it, but the only difference is we will add a custom image to the button instead of text.

Following is the pictorial representation of using Image Buttons in android applications.

In android, we have different types of buttons available to use based on our requirements, those are Button, ImageButton, ToggleButton, and RadioButton.

In android, we can add an image to the button by using attribute android:src in XML layout file or by using the setImageResource() method.

In android, we can create ImageButton control in two ways either in the XML layout file or create it in the Activity file programmatically.

Читайте также:  Cue to iso android

Create ImageButton in XML Layout File

Following is the sample way to define ImageButton control in XML layout file in android application.

xml version= «1.0» encoding= «utf-8» ?>
LinearLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :orientation= «vertical» android :layout_width= «match_parent»
android :layout_height= «match_parent» >
ImageButton
android :id= «@+id/addBtn»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :src= «@drawable/add_icon»/>
LinearLayout >

If you observe above code snippet, here we defined ImageButton control and we are showing the image from drawable folder using android:src attribute in xml layout file.

Create ImageButton Control in Activity File

In android, we can create ImageButton control programmatically in activity file based on our requirements.

Following is the example of creating ImageButton control dynamically in an activity file.

LinearLayout layout = (LinearLayout)findViewById(R.id. l_layout );
ImageButton btn = new ImageButton( this );
btn.setImageResource(R.drawable. add_icon );
layout.addView(btn);

Anndroid Handle ImageButton Click Events

Generally, whenever the user clicks on ImageButton, the ImageButton object will receives an on-click event.

In android, we can define button click event in two ways either in XML layout file or create it in Activity file programmatically.

Define ImageButton Click Event in XML Layout File

We can define click event handler for button by adding android:onClick attribute to the element in our XML layout file.

The value of android:onClick attribute must be the name of method which we need to call in response to a click event and the Activity file which hosting XML layout must implement the corresponding method.

Following is the example of defining a button click event using android:onClick attribute in XML layout file.

android :onClick= «addOperation»/>
LinearLayout >

In Activity that hosts our XML layout file, we need to implement click event method like as shown below

/** Called when the user touches the button */
public void addOperation(View view) <
// Do something in response to button click
>

Define ImageButton Click Event in Activity File

In android, we can define ImageButton click event programmatically in Activity file rather than XML layout file.

To define button click programmatically, create View.OnClickListener object and assign it to the button by calling setOnClickListener(View.OnClickListener) like as shown below.

ImageButton btnAdd = (ImageButton)findViewById(R.id. addBtn );
btnAdd.setOnClickListener( new View.OnClickListener() <
public void onClick(View v) <

// Do something in response to button click
>
>);
>

This is how we can handle ImageButton click events in android applications based on our requirements.

Android ImageButton Control Attributes

Following are some of the commonly used attributes related to ImageButton control in android applications.

Attribute Description
android:id It is used to uniquely identify the control
android:src It is used to specify the source file of an image
android:background It is used to set the background color for an image button control.
android:padding It is used to set the padding from left, right, top and bottom of the image button.
android:baseline It is used to set the offset of the baseline within the view.

Android ImageButton Control Example

Following is the example of defining a one ImageButton and two EditText controls in LinearLayout to get the data of EditText controls when click on ImageButton in android application.

Create a new android application using android studio and give names as ButtonExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

xml version= «1.0» encoding= «utf-8» ?>
LinearLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :orientation= «vertical» android :layout_width= «match_parent»
android :layout_height= «match_parent» android :id= «@+id/l_layout» >
TextView
android :id= «@+id/fstTxt»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :layout_marginTop= «150dp»
android :text= «First Number»/>
EditText
android :id= «@+id/firstNum»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :ems= «10»/>
TextView
android :id= «@+id/secTxt»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :text= «Second Number»
android :layout_marginLeft= «100dp»/>
EditText
android :id= «@+id/secondNum»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :ems= «10»/>
ImageButton
android :id= «@+id/addBtn»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :src= «@drawable/add_icon»/>
LinearLayout >

If you observe above code we created one ImageButton, two TextView controls and two EditText controls in XML Layout file.

Once we are done with the creation of layout with required control, we need to load the XML layout resource from our activity onCreate() callback method, for that open main activity file MainActivity.java from \java\com.tutlane.buttonexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.buttonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity <
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
final EditText firstNum = (EditText)findViewById(R.id. firstNum );
final EditText secNum = (EditText)findViewById(R.id. secondNum );
ImageButton btnAdd = (ImageButton)findViewById(R.id. addBtn );
btnAdd.setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
if ( firstNum .getText().toString().isEmpty() || secNum .getText().toString().isEmpty())
<
Toast.makeText(getApplicationContext(), «Please fill all the fields» , Toast. LENGTH_SHORT ).show();
>
else <
int num1 = Integer.parseInt( firstNum .getText().toString());
int num2 = Integer.parseInt( secNum .getText().toString());
Toast.makeText(getApplicationContext(), «SUM = » + (num1 + num2), Toast. LENGTH_SHORT ).show();
>
>
>);
>
>

If you observe above code we are calling our layout using setContentView method in the form of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file name activity_main and we are getting the values from two EditText controls on ImageButton click and performing an addition operation.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework to get the required layout for an activity.

Output of Android ImageButton Example

When we run the above example using an android virtual device (AVD) we will get a result like as shown below.

This is how we can use ImageButton control in android applications to perform required operations on ImageButton tap or click based on our requirements.

Источник

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:

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 songs with lyrics
Оцените статью