问题
I am trying to keep track of the bounding Rect
for a child TextView
inside of a class extending LinearLayout
I am using View.getGlobalVisibleRect(Rect)
in order to get the TextView's bounding box relative to its parent. It works great on some devices, but there is obviously some kind of unit issue going on on other phones. Simple example of what I'm seeing:
//Extended LinearLayout's onDraw
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
TextView tv = (TextView)findViewById(R.id.textView1);
Rect bounds = new Rect();
tv.getGlobalVisibleRect(bounds);
canvas.drawRect(bounds, myPaint);
}
Whats expected is that it should draw a box under the the TextView tv. It does on my 3.1 tablet, but on my 1.6 and 2.3 phones it draw the box underneath of the TextView. It seems that I need to convert the values of the bounding box to a differnt kind of pixel unit in order to get the results I expect consistently.
Problem is I am not sure if the Rect returned is already in DIP or standard pixels. I have tried doing both:
bounds.top = TypedValue.complexToDimensionPixelSize(bounds.top, getContext().getResources().getDisplayMetrics());
and
bounds.top = TypedValue.COMPLEX_UNIT_DIP, bounds.top, getContext().getResources().getDisplayMetrics());
But neither of these seems to be converting the box top to where it should be. I would greatly appreciate any feedback or advice.
Thanks!
回答1:
Turns out that getGlobalVisibleRect
is either broken pre-3.0 or doesn't return what I am expecting. I found that I could do this instead.
TextView tv = (TextView)findViewById(R.id.textView1);
Rect bounds = new Rect(tv.getLeft(), tv.getTop(), tv.getRight(), tv.getBottom());
来源:https://stackoverflow.com/questions/6922074/drawrect-unit-issues-android