开发者

onClickListener on a LinearLayout

开发者 https://www.devze.com 2022-12-17 05:38 出处:网络
Got a little problem with a functionality I\'d like to implement. I\'ve got a LinearLayout, containing 2 TextViews. I\'d want to set 开发者_如何学Goa onClickListener on it, so that it would behave ju

Got a little problem with a functionality I'd like to implement.

I've got a LinearLayout, containing 2 TextViews. I'd want to set 开发者_如何学Goa onClickListener on it, so that it would behave just like an item in a ListView.

I've tried some possible implementation of this, and got it working using the xml attribute android:onClick of the LinearLayout.

As I want the application to visually react to a click on the LinearLayout (as in a ListView), I put this in the listener callback method :

l.setBackgroundColor(android.R.drawable.list_selector_background);

l is a LinearLayout object, initialised with findViewById();

I get an application not responding whenever I try to click on the layout. I tried to replace the code in the callback method by a Toast message show up, and it works, so I guess the problem is in the setBackgroundColor.

Is anyone familiar with this?

PS: sorry, I can't post more code right now, I'm at work.


You have to set LinearLayout attribute android:clickable="true" in the xml layout file or setClickable(true) in the java activity code.


i noticed that all the advices above don't helpt as long as any of the child elements inside the LinearLayout has the attribute android:textIsSelectable="true".


I found that that setClickable(true) would still cause clicks to go to children of the linearlayout. I found that to have the LinearLayout capture the touch instead of it's children I had to override the dispatchTouchEvent method so I created a subclass of LinearLayout for just this purpose. Seems like an ugly solution though.


you should set the LinearLayout's focusable to true and set all the children view's focusable to false, don't use the android:clickable="true", but you can't see the effect of the click of the linelayout. BTW, the best way is to implement the onTouchEvent api.


android:clickable="true" works perfectly under one condition. Youhave to put the childs inside the LilnearLayout to android:clickable="false".


Had the same problem, I've been trying for an hour all the answers in SO but none worked.

Then I realized I just had to promote my LinearLayout to the bottom of the layout, since other views blocked it, and then it worked, without adding ANY special attributes to the layout.

Putting it here in case it might help someone someday.

0

精彩评论

暂无评论...
验证码 换一张
取 消