Android image button add image

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.

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.

Источник

Android ImageButton selector example

By mkyong | Last updated: August 29, 2012

Viewed: 287,123 (+122 pv/w)

In last Android tutorial, you use “ ImageButton ” to display a “ Button ” with a customized background image easily. However, you can do more than that just a simple image, Android allow you to change the button’s image depends on different states like button is focused or button is pressed.

This example is referenced from this Android custom button article, with minor changes.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Add Images to Resources

Prepare 3 images for button states, and put it into “resource/drawable” folder.

  1. button_normal_green.png – Default image button.
  2. button_focused_orange.png – Display when button is focused, for example, when phone’s keypad is move (focus) on this button.
  3. button_pressed_yellow.png – Display when button is pressed.

2. Add Selector for different button states

Now, create a new XML file in “res/drawable/” folder, in whatever name you want, in this case, we just give a name as “ new_button.xml “. This file defined which button state is belong to which image.

Now, you can refer to this button via this Id : @drawable/new_button .

3. Add Button

Open “res/layout/main.xml” file, add a normal button, and attach the background image to above “new_button” via “ android:background=»@drawable/new_button ”

4. Code Code

A normal button with a simple click listener.

5. Demo

Run the application.

1. Result, default button. (button_normal_green.png)

2. Button is focused. (button_focused_orange.png)

3. Button is pressed. (button_pressed_yellow.png)

Download Source Code

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

This tutorial still can be use. AWESOME !!

Thanks for explaining this so well, It really helps me in understanding basic android concepts of xml.

Thanks for sharing this is Really helped me, ur explanation is very clear and u added the downloadable file thats add the advantage to rectify errors more accurately рџ™‚ Good Work Keep Going

Nice, but I have a question about it.
I would like to have a kind of state on this image button.

I now have a toggle button like this.

private OnClickListener powerButtonListener = new OnClickListener() <
public void onClick(View arg0) <
ToggleButton powerButton = (ToggleButton) arg0;
if (D) Log.d(TAG, “powerButtonListener” + powerButton.isChecked());
searchAndConnect();
if (powerButton.isChecked()) <
powerOn = 1;
sendColorToArm();
> else <
powerOn = 0;
sendColorToArm();
if (mBTSerialService != null) mBTSerialService.stop();
>
>
>;

(My image’s are in a xml file called on_btnaction.xml)

in mainActivity.java.
public class mainActivity extends Activity <
ImageButton on_btnaction;

@Override
public void onCreate(Bundle savedInstanceState) <
on_btnaction = (ImageButton) findViewById(R.id.on_btnaction);
on_btnaction.setOnClickListener(on_btnactionListener);
>

private OnClickListener on_btnactionListener = new OnClickListener() <
public void onClick(View arg0) <
ImageButton on_btnaction = (ImageButton) arg0;
if (D) Log.d(TAG, “on_btnactionListener” + on_btnaction.getDrawableState());
searchAndConnect();
if (on_btnaction.getDrawableState(1)) <
powerOn = 1;
sendColorToArm();
> else <
powerOn = 0;
sendColorToArm();
if (mBTSerialService != null) mBTSerialService.stop();
>
>
>;

Well, what do you think and what do I have to do to make the ImageButon like the ToggleButton?
Thanks in advance.

Источник

Читайте также:  Минусы айфона при переходе с андроида
Оцените статью