How to know whether View inside Scroll is Visible completely or no

There is scroll view between header(at the top of screen) and Tabs(Bottom of the screen). I want to know that whether the ImageView which is inside the ScrollView is fully visible or not on phone screen window.


I would suggest to do the following way (the approach is similar to one in this question).

Eg You have the following xml (I'm not sure what are header and tabs so they are missed):

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/scroller">
        <ImageView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:id="@+id/image"
            android:src="@drawable/image001"
            android:scaleType="fitXY" />
</ScrollView>

Then activity might look like the following:

public class MyActivity extends Activity {

    private static final String TAG = "MyActivity";

    private ScrollView mScroll = null;
    private ImageView mImage = null;

    private ViewTreeObserver.OnGlobalLayoutListener mLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            final Rect imageRect = new Rect(0, 0, mImage.getWidth(), mImage.getHeight());
            final Rect imageVisibleRect = new Rect(imageRect);

            mScroll.getChildVisibleRect(mImage, imageVisibleRect, null);

            if (imageVisibleRect.height() < imageRect.height() ||
                    imageVisibleRect.width() < imageRect.width()) {
                Log.w(TAG, "image is not fully visible");
            } else {
                Log.w(TAG, "image is fully visible");
            }

            mScroll.getViewTreeObserver().removeOnGlobalLayoutListener(mLayoutListener);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Show the layout with the test view
        setContentView(R.layout.main);

        mScroll = (ScrollView) findViewById(R.id.scroller);
        mImage = (ImageView) findViewById(R.id.image);

        mScroll.getViewTreeObserver().addOnGlobalLayoutListener(mLayoutListener);
    }
}

In case of small image it will log: image is fully visible.

However, You should be aware about the following inconsistency (as per my understanding): if You have big image, but doing scaling to it (eg you set android:layout_width="wrap_content" ) when it will look scaled, but actual ImageView height will be as full height of the image (and ScrollView will be even scrolling), so adjustViewBounds might be needed. The reason for that behavious is that FrameLayout doesn't care about layout_width and layout_height of childs.

链接地址: http://www.djcxy.com/p/13714.html

上一篇: grep只能显示匹配搜索模式的文字吗?

下一篇: 如何知道Scroll里面的View是完全可见还是不可见