简体   繁体   English

单击其子级时更改其父级的背景颜色

[英]Change parent's background color when its child is clicked

I have a TableRow which contains a LinearLayout, and then this LinearLayout contains a TextView. 我有一个TableLine,其中包含LinearLayout,然后此LinearLayout包含TextView。 What I want is, once the TextView is clicked, the entire TableRow would change its background color. 我想要的是,一旦单击TextView,整个TableRow就会更改其背景颜色。

I've tried to use getParent() and performClick() to pass the click event from TextView to TableRow. 我试图使用getParent()和performClick()将click事件从TextView传递到TableRow。 The onClick() method of TableRow does get called, but its background color does not change. 确实会调用TableRow的onClick()方法,但其背景颜色不会改变。

Of course I've set the selector by using either 当然,我可以通过使用

row.setBackgroundResource(R.drawable.menu_item_bgcolor);

or 要么

row.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.menu_item_bgcolor));

Doesn't work. 不起作用 Can anyone provide any insight into this? 谁能对此提供任何见解? Thanks, 谢谢,

Below is the selector xml file: 以下是选择器xml文件:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true" android:drawable="@drawable/menu_item_pressed" />
<item android:state_focused="true" android:drawable="@drawable/menu_item_pressed" />
<item android:drawable="@drawable/menu_item_normal" />

</selector>

try this 尝试这个

StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},
    getResources().getDrawable(R.drawable.pressed));
states.addState(new int[] {android.R.attr.state_focused},
    getResources().getDrawable(R.drawable.focused));
states.addState(new int[] { },
    getResources().getDrawable(R.drawable.normal));
row.setImageDrawable(states);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM