Android image button images

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.

Читайте также:  Scaciati igri na android

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.

Источник

How to get image from an ImageButton?

I’m not sure about the code, but I tried doing this:

But that didn’t work, the Imagebutton was shrinked for some reason, there was no image, just a gray rectangle.

5 Answers 5

This will return the id of the View not the image resource associated with it. So you won’t be having a resource related to this that is why you are not seeing the Image .

Set a valid drawable to setImageResource Some thing like R.drawable.drawable_id

This will help get the drawable object and set the drawable object.You can also get the Bitmap object for image drawable This will set the exact drawable associated with the imagebutton

You need to set the ID of drawable resource but you are setting ID of the ImageButton as image resource.

here stuff.getId() returns R.id.stuff .

set the valid drawable resource like

Not the answer you’re looking for? Browse other questions tagged android imagebutton or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Android: Create a toggle button with image and no text

is it possible to create a toggle button in Android that has an image but no text? Ideally it would look like this:

Ive seen similar posts where the answer was to change the background but i want to preserve the Holo Light layout and just swap the text with an image.

I need to be able to programaticallly change the image source,

Any ideas how i would make this?

If this cant be done, is there a way i can make a normal button toggle on and off?

4 Answers 4

Can I replace the toggle text with an image

No, we can not, although we can hide the text by overiding the default style of the toggle button, but still that won’t give us a toggle button you want as we can’t replace the text with an image.

How can I make a normal toggle button

Create a file ic_toggle in your res/drawable folder

Here @drawable/ic_slide_switch_on & @drawable/ic_slide_switch_off are images you create.

Then create another file in the same folder, name it ic_toggle_bg

Now add to your custom theme, (if you do not have one create a styles.xml file in your res/values/ folder)

This creates a custom toggle button for you.

How to use it

Use the custom style and background in your view.

Источник

Читайте также:  Javascript установить для андроид
Оцените статью