我正在嘗試在ImageView的特定區域的中心創建動態按鈕。爲了找出任何區域的中心,我使用這個功能:Android-視圖高度在運行時間內發生變化
TextView createButton(int i, String[] boundingBoxArray) {
String[] coorArray = boundingBoxArray[i].split(",");
int[] coordinates = new int[4];
int x11 = Integer.parseInt(coorArray[0].replace(" ", ""));
int y11 = Integer.parseInt(coorArray[1].replace(" ", ""));
int x22 = Integer.parseInt(coorArray[2].replace(" ", ""));
int y22 = Integer.parseInt(coorArray[3].replace(" ", ""));
coordinates[0] = x11;
coordinates[1] = y11;
coordinates[2] = x22;
coordinates[3] = y22;
TextView buttonn = new TextView(context);
buttonn.setText(String.valueOf(i + 1));
buttonn.setTextSize(15);
buttonn.setId(i + 1);
buttonn.setBackgroundResource(R.drawable.circle);
RelativeLayout.LayoutParams rel_btn
= new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
Rect bounds = imageView.getDrawable().getBounds();
int scaledHeight = bounds.height();
int scaledWidth = bounds.width();
double scale;
double differWidth = 0;
double differHeight = 0;
imageViewHeight = imageView.getHeight();
imageViewWidth = imageView.getWidth();
if (scaledHeight > scaledWidth) {
scale = ((double) imageViewHeight/(double) scaledHeight);
differWidth = (imageViewWidth - (scaledWidth * scale))/2;
} else {
scale = ((double) imageViewWidth/(double) scaledWidth);
differHeight = (imageViewHeight - (scaledHeight * scale))/2;
}
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int swidth = displaymetrics.widthPixels;
int buttonWidth = swidth/30;
double a = ((double) (x11 + x22)/2) * scale - buttonWidth + differWidth;
double b = ((double) (y11 + y22)/2) * scale - buttonWidth + differHeight;
rel_btn.leftMargin = (int) a;
rel_btn.topMargin = (int) b;
rel_btn.width = 2 * buttonWidth;
rel_btn.height = 2 * buttonWidth;
buttonn.setGravity(Gravity.CENTER);
buttonn.setLayoutParams(rel_btn);
return buttonn;
}
當活動開始時,這個函數被調用在for循環(循環的數量取決於區域的數目)對ImageView的創建按鈕。當所有按鈕都被創建時,用戶可以點擊任一個動態按鈕來關注特定區域。
如果用戶點擊任何按鈕,會再次調用createButton()函數(它並不是必需的,但它也沒有提出任何問題)。
問題是ImageView的高度不固定。在第一次調用createButton()函數時,高度將返回大於正常高度。然後,如果再次調用createButton(),高度將返回正常值。
imageViewHeight = imageView.getHeight();
imageViewWidth = imageView.getWidth();
該類有2-3個嵌套線程,所以也許這是問題的原因。但我想很多事情,如:
- 我使用CountDownLatch處理線程和功能
- 我用mImageView.post(新的Runnable ...),以確保創建的ImageView後調用函數。
- 我叫imageView.getHeight()很多 不同的地方,但沒有什麼改變。
我保持表達很長,因爲我無法確定信息是否足以理解。如你所知,英語不是我的本地人。謝謝。編輯:我忘了提及:在API 19下面,一切都很酷(getHeight()的值以正常大小返回,無論是在第一次調用createButton()方法或更高版本時)。 API 20及以上,我得到這個錯誤。
嘗試addOnGlobalLayoutListener()偵聽器像[this](http://stackoverflow.com/a/8171014/4101990) –
@MaheshB我試過,但沒有奏效。同樣的問題發生。 – ACAkgul
爲什麼降低投票率? – ACAkgul