Android on layout clicked

Making a LinearLayout act like an Button

I have a LinearLayout that I’ve styled to look like a button , and it contains a few text/ImageView elements. I would like to make the whole LinearLayout act like a button , in particular to give it states that are defined in a so it has a different background when it is pressed.

Is there a better way than making an ImageButton the size of the whole Layout and positioning absolutely?

10 Answers 10

If you want add the Android default background behavior to make a Layout acts like a «clikable» View , set on the targeted Layout :

API 11+ (Pure Android):

API 7+ (Android + AppCompat Support Library):

Any API:

Answers above still true but didn’t help me for just add the default pressed and released UI state (like in a ListView for instance).

I ran into this problem just now. You’ll have to set the LinearLayout to clickable. You can either do this in the XML with

Or in code with

I used the first and second answer. But my linearlayout has images and text with background color, so i had to change «background» to «foreground»

First you’ll want a selector to define the different states. For example, in an XML file:

I haven’t tried it, but you can possibly set the LinearLayout’s android:background to this selector, and set android:clickable to true and it’ll work.

If it doesn’t, you could switch to using a RelativeLayout, and make the first element a button with this selector as the background and fill_parent for its layout width and height. In this case, just use a regular Button and set android:background to your selector. You don’t have to put text on your button.

In the application I am working I need to create a LinearLayout dynamically. In this case the command

is not working as supposed to do. Although I may miss something, I managed to exploit setOnTouchListener to get the same result and I submit the code in case anyone has the same needs.

The following code creates a LinearLayout with two textviews and round corners, changing color when pressed.

First, create two xml files in drawable folder, one for normal and one for pressed linearlayout state.

Источник

onClick not triggered on LinearLayout with child

I’ve got a custom LinearLayout with a smaller TextView child. I’d like to be able to click the area not covered by the TextView, so I set clickable=true and an onclicklistener to the LinearLayout, but onClick is not triggered. If I set the onclick listener on the TextView it works as expected.

Anybody can help?

My custom LinearLayout

14 Answers 14

android:duplicateParentState=»true» did not help me.

To make your layout clickable with its children you need add this option for every child:

Then click handling will go up to parent.

for every child

Читайте также:  Filmic pro для android

This isn’t your case, but I had similar problem with clickable ViewGroup . After a hour of looking for solution a found out that I set android:inputType to TextView inside my ViewGroup which was blocking onClick() listener (no idea why)

Don’t use android:inputType with TextView

Make Your parent LinearLayout’s android:clickable=»true»

Make all of the the childview’s android:clickable=»false»

Under Linearlayout — Remove android:inputType=»» from TextView

The android:duplicateParentState=»true» made my TextView looks like it’s disabled, and cannot receive click event.

All you need is set the TextView clickable=»false» . So the click event will dispatch to parent layout, and the TextView still can react to touch event (with ripple effect).

Your TextView height covers the whole parent (whole layout) so you might clicking on empty space but not on the layout. Try using wrap_content for android:layout_height for your TextView. Set click listener for the layout as well.

You aren’t using your custom View; you’re using a standard LinearLayout. Your XML tag should be:

One thing to make sure of is that another view is not on top of the view you are trying to click. This is especially common in FrameLayouts (where your sub LinearLayout may be covered) or with Relative Layouts you might have forgot to update this line:

so that views don’t fill the same space.

If the views in question are TextView s, you may need to set them as focusable=»false» so that the first click isn’t used focusing on the text view.

The problem may be from the textview that has android:layout_height=»fill_parent» in its layout. If that doesn’t fix the issue, the problem may be the onClick() event. The linear layout may not actually ever call onClick() since its a layout. Try overriding the onTouch() event listener instead.

Add the following attributes to the linearlayout Any Click events not handled by the child views will be automatically passed over to the LinearLayout.

I faced the same problem, and all the XML Attributes didn’t work. I am not sure if this happens because i programmatically inflate and add the views, but this is how i worked around the problem.

I have a Class which extends LinearLayout, with a TextView and an ImageView. After inflating the layout and getting the views, I assigned the child views a OnClickListener, when pressed, executes the LineaLayout’s onClickListner.

I also tried overriding OnTouchListener, but then my child views didn’t have the ripple effect, which I needed.

None of the solutions above forked for me. Than i noticed that a LinkMovementMethod set to TextView inside my LinearLayout . This class intercepts touch events, click events and properties of TextView such as clickable, focusable vs..

Источник

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:
Читайте также:  Shareman android что это

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.

Читайте также:  Android что такое cayenne

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.

Источник

Button Click Me setOnClickListener Method Working — Java Android

Button will respond to OnClickListener after this course.

This example demonstrates the implement button onclicklistener android java Code Example

In this article, we will discuss about how to trigger click events on android Views (Buttons, Text views etc) ?

Android Button in JAVA ANDROID

Action listeners are probably the easiest — and most common — event handlers to implement. You implement an action listener to define what should be done when an user performs certain operation.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Create Empty Project

How to implement on Android Button OnClick in android programmatically.

S tep 2 — “Add the following code to res/layout/activity_main.xml.“

I worked in simple relative layout method for only give basic example.

  • In the below code, we have declared Button as ”@+id/button”.
  • You can add a spinner to your layout with the Button object. You should usually do so in your XML layout with a element. For example:

Источник

Android clickable layout

У меня есть линейный макет, который я установил true для кликирования + фокуса. Но проблема в том, что при щелчке не отображается фокус. Как я могу получить фокус, который будет отображаться.

Я думаю, вам нужно установить в качестве фона для интерактивного представления (макета) список состояний , который можно вывести , это ресурс, для которого вы можете указать разные чертежи для разных состояний или комбинаций состояний, есть один для выбора, один для нажатия и т. Д. на. Кроме того, состояние макета распространяется на всех его дочерних элементов.

CLARIFICATIONS – это пример из ранее связанных документов:

res/drawable/button.xml : (это список доступных состояний)

button_pressed , button_focused и button_normal – обычные button_normal , представляющие кнопку в этих состояниях, возможно, png (так что нажатие может быть вставкой, сфокусировано выделено оранжевым цветом).

Если вы установите этот ресурс в качестве фона для вашей «линейной кнопки макета»:

Теперь фокусировка макета автоматически устанавливает фоновое изображение на @drawable/button_focused и т. Д.

Конечно, все используемые вами чертежи должны быть ресурсами в res/drawable/ вместе с button.xml .

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

@danLeon: Вместо андроида: background = «@ android: drawable / btn_default»

Вы должны использовать
Android: фон = «@ андроид: рисуем / list_selector_background»

Прежний также изменит пользовательский интерфейс, что не требуется.

Попытайтесь привести этот макет в начало кода:

Если это не сработает, проверьте, нет ли одного или нескольких совпадений над этим LinearLayout.

Возможно, это образец макета, который может дать вам некоторую идею:

Простым способом является установка этого атрибута: android:background=»@android:drawable/btn_default»

Источник

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