Android java imagebutton example

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

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

ImageButton

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

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

Source for ImageButton

Методы

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

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

Примеры

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

android.resource://[пакет]/[идентификатор ресурса]

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

 Uri uri = Uri.parse("android.resource://ru.alexanderklimov.imagebuttondemo/" + R.drawable.cat); 

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

android.resource://[пакет]/[тип ресурса]/[имя ресурса]

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

 Uri uri = Uri.parse("android.resource://ru.alexanderklimov.imagebuttondemo/drawable/cat"); imageButton.setImageUri(uri); 

Щелчок

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

 . ImageButton imageButton; boolean flag = true; imageButton.setOnClickListener(new View.OnClickListener() < public void onClick(View v) < // меняем изображение на кнопке if (flag) imageButton.setImageResource(R.drawable.cutecat4); else // возвращаем первую картинку imageButton.setImageResource(R.drawable.cutecat2); flag = !flag; >>); 

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

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

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

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

 imageButton.setOnLongClickListener(new OnLongClickListener() < @Override public boolean onLongClick(View v) < Toast toast = Toast.makeText(getApplicationContext(), "Long Click", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); return false; >>); 

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

Читайте также:  Html position left to right

Источник

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.

Android Buttons with Example

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.

Create ImageButton in XML Layout File

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

< 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»/>

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.

Читайте также:  example-current-time-function | w3resource

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

< 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»

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

< 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»/>

Читайте также:  Server monitor v. >

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 color: #660e7a;»>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.

Источник

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