How to set onClickListener to the WHOLE screen in Android?

天涯浪子 提交于 2020-01-04 02:45:48

问题


The xml layout file looks like:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout  android:id="@+id/my_rootViewID"
    <LinearLayout>

        <ImageView/>

        <TextView/>

        <ImageView/>

    </LinearLayout>
</FrameLayout>

I have tried this:

my_view = findViewById(R.id.my_rootViewID);
my_view.setOnClickListener( new My_OnClickListener() );

My problem: This works only with the ImageViews, but the TextView is not clickable. I could set OnClickListener specifically to the TextView as well, but I have many TextViews (in other cases), so adding theese listeners would be very slow, and elaborate.


回答1:


You can do this:

ViewTreeObserver viewTreeObserver = myView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {...}

From the docs of ViewTreeObserver:

A view tree observer is used to register listeners that can be notified of global changes in the view tree. Such global events include, but are not limited to, layout of the whole tree, beginning of the drawing pass, touch mode change




回答2:


You can add a transparent view over your layout and set listener for this view. It will intercept all click events.



来源:https://stackoverflow.com/questions/17999737/how-to-set-onclicklistener-to-the-whole-screen-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!