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;
}
活動を開始すると、この関数はImageViewの上のボタンを作成するために、(ループの数は、領域の数に依存している)forループで呼ばれています。すべてのボタンが作成されると、ユーザーは任意の動的ボタンの1つをクリックして、特定の領域に集中することができます。
ユーザーがボタンをクリックすると、createButton()関数がもう一度呼び出されます(必要ではありませんが、問題の原因になります)。
問題はImageViewの高さが修正されていないことです。 createButton()関数を呼び出す最初に、高さは通常の高さよりも大きくなります。 createButton()をもう一度呼び出すと、heightは通常の値を返します。
imageViewHeight = imageView.getHeight();
imageViewWidth = imageView.getWidth();
クラスには2〜3個のネストされたスレッドがあるため、これが問題の原因になる可能性があります。しかし、私はのようなものがたくさん試した:私はスレッドと機能
- を私はImageViewのが作成された後の関数を呼び出してくださいするmImageView.post(新しいRunnableを...)を使用しました。
- 私はimageView.getHeight()を の異なる場所にたくさん呼びましたが、何も変更されていません。
情報が十分であるかどうかを判断できなかったので、私は式を長くしています。そして、あなたが気づくように、英語は私の母国語ではありません。ありがとうございました。
編集:私は言及を忘れていました:API 19以下では、getHeight()の値はcreateButton()以降の呼び出し時のいずれかで正常です。 API 20以上では、このエラーが発生します。
[this](http://stackoverflow.com/a/8171014/4101990)のようなaddOnGlobalLayoutListener()リスナーを試してください。 –
@MaheshB私は試しましたが、それはできません。同じ問題が発生します。 – ACAkgul
なぜそれはdownvotedですか? – ACAkgul