Android:如何将点击事件传播到 LinearLayout 孩子并更改其可绘制对象 [英] Android: How to propagate click event to LinearLayout childs and change their drawable

查看:26
本文介绍了Android:如何将点击事件传播到 LinearLayout 孩子并更改其可绘制对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类似于 ImageButton 的线性布局.

I would like to create a linear layout which would behave similarly to ImageButton.

<LinearLayout
    android:id="@+id/container"
    style="?WidgetHomeIconContainer">            

    <ImageView
        android:id="@+id/icon"
        style="?WidgetHomeIcon" />

    <TextView
        android:id="@+id/title"
        style="?WidgetHomeLabel"             
        android:text="@string/title"
        android:textAppearance="?attr/TextHomeLabel" />
</LinearLayout>

在 ImageView、TextView 和 LinearLayout 的样式中,我为所有状态设置了一个选择器.

In styles of ImageView, TextView and LinearLayout, I set a selectors for all states.

现在:

  • 当我单击 ImageView 时(我也使用 ImageButton 进行了尝试) - 它的行为正确,并且图像会根据选择器 xml 进行更改.
  • 当我点击 LinearLayout 时 - 点击了线性布局,但 ImageView 和 TextView 并没有改变它的可绘制/外观

所以我想做以下事情.当我单击父 LinearLayout 时,我需要将其所有子项更改为按下状态.

So I would like to do the following. When I click on parent LinearLayout, I need to change all it's childs to pressed state.

我尝试将以下代码添加到 LinearLayout onClickListener 以传播点击:

I tried to add following code to LinearLayout onClickListener to propagate the click:

@Override
public void onClick(View v)
{
    LinearLayout l = (LinearLayout) v;
    for(int i = 0; i < l.getChildCount(); i++)
    {
        l.getChildAt(i).setClickable(true);
        l.getChildAt(i).performClick();
    }
}

但它仍然是一样的.非常感谢您的帮助.

But it still reamins the same. Thank you very much for any help.

推荐答案

Put

android:duplicateParentState="true"

在您的 ImageView 和 TextView..然后视图获得其可绘制状态(聚焦,按下等)从其直接父级而不是从其自身.

in your ImageView and TextView..then the views get its drawable state (focused, pressed, etc.) from its direct parent rather than from itself.

这篇关于Android:如何将点击事件传播到 LinearLayout 孩子并更改其可绘制对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆