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

后端 未结 5 462
滥情空心
滥情空心 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 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)

提交回复
热议问题