Finding the View location (position) on display (screen) in android

后端 未结 5 433
滥情空心
滥情空心 2020-12-19 04:50

I want to find the view\'s position on the display screen.

To do it, I use the methods such as view.getLeft() ,view.getBottom() , vi

相关标签:
5条回答
  • 2020-12-19 04:57

    the methods u have written is enough to find the location on screen, but the place where you have written is not correct.

    try to write the methods (view.getLeft(), view.getTop()... etc) in onWindowFocusChanged(boolean hasFocus) method.

    for example...

    **

    @Override
        public void onWindowFocusChanged(boolean hasFocus) {
            super.onWindowFocusChanged(hasFocus);
            if (hasFocus) {
                    System.out.println("Right:"+tv2.getRight());
                    System.out.println("Left:"+tv2.getLeft());
                    System.out.println("Top:"+tv2.getTop());
            }
        }
    

    **

    it will solve your issue.

    0 讨论(0)
  • 2020-12-19 05:00

    Easiest way is to get it using View.getLocationOnScreen(); OR getLocationInWindow();

    And if you want position relative to root Layout then See

    0 讨论(0)
  • 2020-12-19 05:11

    Use the getLeft(), getRight(), getTop(), and getBottom(). These can be used after the view is instantiated.

    0 讨论(0)
  • 2020-12-19 05:14

    I'm not sure that you can get the position of the view before the layout phase have been done. Once the view is layed out you can use getLocationOnScreen to get the position of the view. getTop and similar only returns the position of the view in its parent.

    0 讨论(0)
  • 2020-12-19 05:23

    You really can't get the view before hand. You may want to do an explicit using invalidate() if possible or you can check this in the onPostResume() or onResume() function.

    If you're just trying things out and want to have fun with threads, this code block will put your code onto the UI thread and will wait for everything to be rendered and then display your code:

    final View gv = this;
    ViewTreeObserver vto = gv.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @SuppressLint("NewApi")
        public void onGlobalLayout() {
            gv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    
            tv1=(TextView)findViewById(R.id.tv1);
            tv2=(TextView)findViewById(R.id.tv2);
            System.out.println("tv4 width:"+tv2.getWidth());
            System.out.println("tv4 height:"+tv2.getHeight());
            System.out.println("Right:"+tv2.getRight());
            System.out.println("Left:"+tv2.getLeft());
            System.out.println("Top:"+tv2.getTop());
            System.out.println("Bottom:"+tv2.getBottom());
    }
    

    This last one is pretty heavy duty lifting but it will get the job done. I usually put any lines like this in my logs(i.e. android.util.Log)

    0 讨论(0)
提交回复
热议问题