问题
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