Câu hỏi này đã được hỏi nhiều lần, nhưng mọi người đều cho biết lý do tại sao điều này xảy ra (tức là tính toán xảy ra trước khi bố cục được đặt). Nhưng tôi cần giải pháp cho việc này. Tôi đã thử getBottom();
, getTop();
, getLocationOnScreen(int[] location);
. Nhưng tất cả trả về giá trị Zero (0). Tôi thậm chí đã cố gắng đưa ra những điều này trong onStart();
, để cho thời gian bố trí được đặt, nhưng không có may mắn. Đây là mã của tôi:Phương thức lấy vị trí xem trả lại 0
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
Log.d("getBottom :", Integer.toString(tv.getBottom()));
Log.d("gettop :", Integer.toString(tv.getTop()));
int[] location = new int[2];
tv.getLocationOnScreen(location);
Log.d("getlocationonscreen values :", Integer.toString(location[0])+" "+Integer.toString(location[1]));
}
@Override
protected void onStart() {
Log.d("getBottom in onStart :", Integer.toString(tv.getBottom()));
Log.d("gettop in onStart :", Integer.toString(tv.getTop()));
int[] location = new int[2];
tv.getLocationOnScreen(location);
Log.d("getlocationonscreen in onStart :", Integer.toString(location[0])+" "+Integer.toString(location[1]));
super.onStart();
}
Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="156dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
lần nữa, tôi xin lỗi vì lặp lại những câu hỏi. Cảm ơn trước.
Bạn có thể giải thích thêm một chút về vấn đề chính xác của bạn không. những gì sẽ sai trong mã trên. –